55

How can i configure a shared config block for a set of locations?

    location / {

            proxy_pass        http://127.0.0.1:9000/;
            proxy_redirect    off;
            proxy_set_header  Host             $http_host;
            proxy_set_header  X-Real-IP        $remote_addr;
            proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;

            proxy_cache cache-test;
            proxy_cache_valid 200 302 24h;
            proxy_cache_valid 404 60s;
            add_header X-Cache-Status $upstream_cache_status;

    }


    location /api/0.1/user{
            proxy_cache_key /user/$http_authorization;
    }

Now if i try to access /api/0.1/user then i will get 404 because it doesn´t pass the request to 127.0.0.1:9000

SleighBoy
  • 878
  • 6
  • 7
netbrain
  • 703
  • 1
  • 6
  • 11

2 Answers2

70

Create a common proxy config and include as-needed.

/etc/nginx/api_proxy.conf

proxy_pass        http://127.0.0.1:9000/;
proxy_redirect    off;
proxy_set_header  Host             $http_host;
proxy_set_header  X-Real-IP        $remote_addr;
proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;

proxy_cache cache-test;
proxy_cache_valid 200 302 24h;
proxy_cache_valid 404 60s;
add_header X-Cache-Status $upstream_cache_status;

Your Host Config File

...
location /api/0.1/user {
    include /etc/nginx/api_proxy.conf;
    proxy_cache_key /user/$http_authorization;
}
...
SleighBoy
  • 878
  • 6
  • 7
  • 2
    +1, but just one note: turns out you can include whole bunch of configuration this way including the whole location http://nginx.org/en/docs/ngx_core_module.html#include – equivalent8 Aug 11 '14 at 09:47
  • ...or my example https://github.com/equivalent/scrapbook2/tree/master/examples/nginx_shared_configuration – equivalent8 Aug 11 '14 at 11:24
11

Most of proxy_* configuration variables are also allowed within server context, so you can move them up to share same settings over several locations.

However, proxy_pass should be only used within location. So you should have at least this directive within each location, optionally overriding values of some extra proxy_* vars.

  • 3
    This won't work if you have location-specific `proxy_set_header` directives because "These directives are inherited from the previous level if and only if there are no proxy_set_header directives defined on the current level." http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header – Emerson Farrugia Apr 13 '17 at 14:56