Reputation: 4011
What order do location directives fire in?
Upvotes: 337
Views: 187471
Reputation: 3022
It fires in this order.
=
(exactly)
location = /path
^~
(forward match)
location ^~ /path
~
, ~*
(regular expression case sensitive and insensitive)
location ~ /path/
,location ~* .(jpg|png|bmp)
/
location /path
Upvotes: 162
Reputation: 239
Locations are evaluated in this order:
location = /path/file.ext {}
Exact matchlocation ^~ /path/ {}
Priority prefix match -> longest firstlocation ~ /Paths?/ {}
(case-sensitive regexp) and location ~* /paths?/ {}
(case-insensitive regexp) -> first matchlocation /path/ {}
Prefix match -> longest firstThe priority prefix match (number 2) is exactly as the common prefix match (number 4), but has priority over any regexp.
For both prefix matche types the longest match wins.
Case-sensitive and case-insensitive have the same priority. Evaluation stops at the first matching rule.
Documentation says that all prefix rules are evaluated before any regexp, but if one regexp matches then no standard prefix rule is used. That's a little bit confusing and does not change anything for the priority order reported above.
Upvotes: 21
Reputation: 3332
There is a handy online tool for testing location priority now:
location priority testing online
Upvotes: 57
Reputation: 13986
From the HTTP core module docs:
Example from the documentation:
location = / {
# matches the query / only.
[ configuration A ]
}
location / {
# matches any query, since all queries begin with /, but regular
# expressions and any longer conventional blocks will be
# matched first.
[ configuration B ]
}
location /documents/ {
# matches any query beginning with /documents/ and continues searching,
# so regular expressions will be checked. This will be matched only if
# regular expressions don't find a match.
[ configuration C ]
}
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
# Configuration D.
[ configuration E ]
}
If it's still confusing, here's a longer explanation.
Upvotes: 510