How to conditionally match location in nginx

viraptor asked:

I’d like to set up nginx location match but only for a specific source address. Unfortunately if I already match a location, but not the condition I can’t fall through to the next location. What’s the way to solve it nicely?

server {
    ...
    location / {
        index app.php;
        try_files $uri @rewriteapp;
    }
    location @rewriteapp {
        rewrite ^(.*)$ /app.php/$1 last;
    }
    ...
    location ~ ^/admin {
        if ($source_trusted = "UNKNOWN") {
            return 403;
        }
    }
    ...
    location ~ ^/... {
        fcgi_pass ...
        ...
    }
}

With this config going to /admin from a source that sets $source_trusted = OK (via geo module) results in a 404, rather than the page loading.

My answer:


Remember that nginx generally only evaluates one location unless specifically instructed to use another, such as when calling to a named location in try_files (which you do).

So when you hit the ^/admin location, you only need to do whatever is appropriate. In this case, it’s most likely going to be exactly the same try_files as you used in location /.

    location ~ ^/admin {
        if ($source_trusted = "UNKNOWN") {
            return 403;
        }
        try_files $uri @rewriteapp;
    }

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.