I am trying to set up a bunch of virtual hosts on Nginx and I want to set some headers before passing the request upstream. I have some headers that I always want to set and then I have some headers that I want to set for selected location blocks.

Unfortunately, it seems that Nginx does not allow the proxy_set_header directive on multiple levels and as a result, it just clears any headers set in the http block.

Nginx documentation states the following on proxy_set_header:

Allows redefining or appending fields to the request header passed to the proxied server. The value can contain text, variables, and their combinations. These directives are inherited from the previous level if and only if there are no proxy_set_header directives defined on the current level.

So the question is... either Nginx has a disappointing limitation or I am thinking about this problem in the wrong way.

Any ideas on an idiomatic solution to this problem?


Create a file to include in each block that sets the headers you want. (So a common inc-http-headers.conf) that you include in the http block and all of the location blocks that need the common headers.


If you are using OpenResty or at least its headers-more-nginx-module, you can do this with the more_set_input_headers directive.

For example, the following will do what you expect:

http {
    # ...
    more_set_input_headers Foo 1;
    server {
        # ...
        more_set_input_headers Bar 2;
        location / {
            more_set_input_headers Qux 3;
            proxy_pass http://some-server;
            # request to some-server has Foo: 1, Bar: 2, and Qux: 3

There are some quirks to this approach however. You cannot muck with the Connection header this way, you must more carefully manage the cache-related headers than with proxy_set_header (both of these limitations are documented), and in my experience, the effect of more_set_input_headers Host $host is not the same as proxy_set_header Host $host. If you aren't concerned with cache-related headers, then the biggest places these limitations crop up is getting WebSockets to work and working with upstreams that use the Host header in a nontrivial way.

A good rule of thumb I've found is to use proxy_set_header for Connection and Host and more_set_input_headers for everything else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.