Request/response transformation in Nginx - Commands & Configuration
events {}
http {
server {
listen 8080;
location / {
# Change the Host header in the request
proxy_set_header Host example.com;
# Add a custom header to the response
add_header X-Custom-Response "Transformed by Nginx" always;
# Rewrite URL path from /oldpath to /newpath
rewrite ^/oldpath/(.*)$ /newpath/$1 break;
# Proxy pass to backend server
proxy_pass http://localhost:9000;
# Modify response body: replace 'foo' with 'bar'
sub_filter 'foo' 'bar';
sub_filter_once off;
}
}
}
events {}: Required block for Nginx event handling.
http {}: Main block for HTTP server settings.
server {}: Defines a server listening on port 8080.
location / {}: Handles all requests to the root path.
proxy_set_header Host example.com; changes the Host header sent to the backend.
add_header X-Custom-Response "Transformed by Nginx" always; adds a custom header to the response, including for error responses.
rewrite ^/oldpath/(.*)$ /newpath/$1 break; rewrites URLs starting with /oldpath to /newpath.
proxy_pass http://localhost:9000; forwards requests to a backend server running on port 9000.
sub_filter directives replace all occurrences of 'foo' with 'bar' in the response body.
nginx -t
nginx -s reload
curl -i http://localhost:8080/oldpath/test
If you remember nothing else from this pattern, remember: Nginx can change both incoming requests and outgoing responses using simple configuration directives.