nginx - read custom header from upstream server

It's not only possible, it's easy:

in nginx the response header values are available through a variable (one per header). See http://wiki.nginx.org/HttpCoreModule#.24sent_http_HEADER for the details on those variables.

In your examle the variable would be $sent_http_My_custom_header.


I was facing the same issue. I tried both $http_my_custom_header and $sent_http_my_custom_header but it did not work for me.

Although solved this issue by using $upstream_http_my_custom_header.


When using NGINX as a proxy, there are four sets of headers:

  • client -> nginx: the client request headers
  • nginx -> upstream: the upstream request headers
  • upstream -> nginx: the upstream response headers
  • nginx -> client: the client response headers

You appear to be asking about the upstream response headers. Those are found in the $upstream_http_name variables.

However, take into account that any response headers are only set after the headers from the upstream server response have been received. Any if directives are run before sending the upstream request, and will not have access to any response headers! In other words, if directives are run after the client request has been received, before making the upstream request.

If you need to change how a response is handled, you can use a map directive however to set variables based on response headers, then use those variables in add_header (set client response headers), log_format or any othere directives that are active during the response phases (internally named the NGX_HTTP_CONTENT_PHASE and NGX_HTTP_LOG_PHASE phases). For more complex control you'll have to use a scripting add-on such as the Lua module (e.g. using a header_filter_by_lua_block directive).

To read or set individual headers, use:

from to type read (variable) write (directive)
client nginx request $http_name
ngnix upstream request proxy_set_header
upstream nginx response $upstream_http_name
nginx client response $sent_http_name add_header

NGINX copies certain headers from client request to upstream request, and from upstream response to client response using various proxy_ directives, giving you options to omit or explicitly include headers for either direction. So if an upstream response header is only found in $upstream_http_name variables, then those headers were specifically not copied to the client response, and the set of available $sent_http_name variables will include any extra headers set by NGINX that are not present in the upstream response.


Use $http_MY_CUSTOM_HEADER

You can write some-thing like

set my_header $http_MY_CUSTOM_HEADER;
if($my_header != 'some-value') {
#do some thing;
}