When proxying requests to backend servers in Nginx, it's sometimes necessary to add custom headers to the response. This can be achieved using the add_header directive, which is commonly specified within server or location blocks.
Here is an example of adding custom response headers in an Nginx configuration file:
nginxserver { listen 80; server_name example.com; location / { proxy_pass http://backend_server; # This is your backend server address add_header X-Proxy-Cache $upstream_cache_status; # Other proxy settings, such as setting proxy headers proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
In the above configuration, we add a custom response header named X-Proxy-Cache for all requests proxied through the / location block. The value is set to the $upstream_cache_status variable, which typically indicates the caching status of the backend server.
Note that the add_header directive can add both constant values and dynamically generated values using Nginx variables. However, if you use add_header, you must ensure all default headers are included, as it overrides Nginx's default behavior and only outputs headers explicitly defined in your configuration.
The above configuration is a simple example; you can add other response headers or configure more complex settings as needed.