12

I have the need to restrict access to certain files based on a query string parameter. I have an NGINX proxy server that sits in front of several other nginx web servers for load balancing. I have decided to enforce this query string parameter at the proxy server level in order to consolidate the configuration changes. This has added a bit of complexity to my setup because the request can not get trapped in the if as it needs to be sent upstream.

server {
        listen 443;
        # SSL Settings

        server_name staging.xxxx.com;

        location / {
                proxy_pass http://webdav-cluster;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Real-IP       $remote_addr;
                proxy_set_header Host            $http_host;
        }

        # Unless the correct application token is passed in as a query parameter
        # then deny access.
        location ~ \/protected\/.*txt$ {
                if ($arg_secret != abc) {
                        return 403;
                }

                proxy_pass http://webdav-cluster;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Real-IP       $remote_addr;
                proxy_set_header Host            $http_host;
        }
}

Is there a way to store those 4 proxy lines in a location or variable and then internally redirect to that with one line? I may also use the same settings in different virtual hosts.

VBart
  • 14,714
  • 4
  • 45
  • 49
bmckim
  • 143
  • 5

2 Answers2

4

In this case you should use the include directive: http://nginx.org/r/include

VBart
  • 14,714
  • 4
  • 45
  • 49
  • 5
    Technically correct, but it'd be nice to be able to do it without splitting it into several files for small things. – Mahn Oct 26 '13 at 18:37
  • Then use your favourite template engine to generate configs. It could be `bash` as well. – VBart Oct 27 '13 at 12:23
0

I know this is an old question, but it's a top Google result and today I found two alternatives which do not require includeing a separate file.

As a slightly simpler example, assume I want /route1 and /route2 to share the same proxy settings. I can either configure a regex location OR use the try_files directive to force a fallback.

Use a regex to share proxy config for multiple routes

Source: https://serverfault.com/q/564127/805740

location ~ ^/(route1|route2) {
    YOUR_PROXY_CONFIG_HERE
}

Use try_files to force a fallback to a shared proxy config

Source: https://serverfault.com/a/1100562/805740

location /route1 {
    try_files "" @fallback
}
location /route2 {
    try_files "" @fallback
}
location @fallback {
    YOUR_PROXY_CONFIG_HERE
}

Mix and Match

location /route1 {
    try_files "" @fallback
}
location ~ ^/(route2|route3) {
    try_files "" @fallback
}
location @fallback {
    YOUR_PROXY_CONFIG_HERE
}
thehale
  • 913
  • 10
  • 18