How to add a response header on nginx when using proxy_pass?

sorin picture sorin · Jan 24, 2013 · Viewed 157k times · Source

I want to add a custom header for the response received from the server behind nginx.

While add_header works for nginx-processed responses, it does nothing when the proxy_pass is used.

Answer

Oliver picture Oliver · Apr 30, 2013

add_header works as well with proxy_pass as without. I just today set up a configuration where I've used exactly that directive. I have to admit though that I've struggled as well setting this up without exactly recalling the reason, though.

Right now I have a working configuration and it contains the following (among others):

server {
    server_name  .myserver.com
    location / {
        proxy_pass  http://mybackend;
        add_header  X-Upstream  $upstream_addr;
    }
}

Before nginx 1.7.5 add_header worked only on successful responses, in contrast to the HttpHeadersMoreModule mentioned by Sebastian Goodman in his answer.

Since nginx 1.7.5 you can use the keyword always to include custom headers even in error responses. For example:

add_header X-Upstream $upstream_addr always;

Limitation: You cannot override the server header value using add_header.