95

I'm having trouble understanding nested locations in nginx. I have two locations with some configuration directives in common, so rather than repeat the directives, I'd prefer to repeat the URI using a regular-expression:

location ~ /a|/b {
        location /a {
        }
        location /b {
        }
}

However, this gives the error

nginx: [emerg] location "/a" is outside location "/a|/b" in /etc/nginx/nginx.conf:36

Without the or | it seems okay, though.

location ~ /a {
        location /a {
        }
}

What am I doing wrong? Is there a better way to do this without repeating anything? Can I group locations in another way?

4

1 Answer 1

153

Old question, but the issue is because the parent location is a regex location while the nested locations are prefix locations.

When a parent location is defined by a regex, any nested locations must also be defined by regexes:

location ~ ^/(a|b) {
        location ~ ^/a {
        ...
        }
        location ~ ^/b {
        ...
        }
}

You may only define nested prefix locations when the parent location is also a prefix location:

location /a {
        location /a {
               # You can also skip this location and just write
               # your code directly under the parent location
        }
        location /a/b {
        ...
        }
}

However, you may define nested regex locations when the parent location is a prefix location:

location /a/b {
        location ~ /a {
        ...
        }
        location ~ /b {
        ...
        }
}
12
  • I got confused by your first sentence, but your examples make sense. I assume in the last example, the prefix location /b will throw an error?
    – Jayen
    Sep 10, 2014 at 1:33
  • 17
    That first sentence should be in the documentation.
    – AndreKR
    Apr 15, 2015 at 7:13
  • 2
    In the first example, if you leave out the location /a { } boilerplate -- does the order matter?
    – Meekohi
    May 15, 2017 at 20:46
  • 5
    Ah nevermind I misunderstood. The nested locations don't inherit anything from their parent locations.
    – Meekohi
    May 15, 2017 at 20:52
  • The parent location can be a non regex location but any multiple nested locations within the parent have to all be either regex / non regex.
    – MitchellK
    Jun 26, 2018 at 7:45

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.