Nginx Location Matcher
nginx picks a location block by a rule order that surprises people: an exact match beats everything, the longest prefix normally wins, but a ^~ prefix stops the regex pass and a plain prefix can still lose to a regex. Paste the blocks and a URI to see which one answers, and what each of the others did.
Matched block
nginx would hand this request to
- Match kind
- Longest prefix
- Blocks read
| Location | Line | Outcome |
|---|
The order nginx searches
- Exact match first. A block written
location = /pathis compared literally against the request path; if it is equal the search ends there, whatever else is configured. - Then the longest prefix. All blocks without a modifier, and all
^~blocks, are prefix matches; the longest pattern wins. A prefix matches on whole characters, so/apialso matches/apiary, which is why trailing slashes are worth writing deliberately. ^~stops the regex pass. When the winning prefix carries^~, nginx uses it and never tries a regex. Without the modifier, the prefix is only a candidate and a matching regex can still take the request.- Regexes run in file order.
~is case-sensitive and~*is case-insensitive. The first regex that matches wins and the search ends, so a broad pattern placed above a narrow one shadows it. - Falling back. If no regex matches, the longest prefix from step 2 answers. If nothing matches at all, nginx returns 404 unless a server-level
try_filesor error page sends the request elsewhere. - Named locations are not candidates. A block named
@fallbackcan only be reached by an explicit reference such astry_files … @fallbackorerror_page 404 @fallback, never by a URI, so it is listed but never matched.
What is not modelled. The URI is matched after the query string is removed, but percent-encoding, dot segments and repeated slashes are not normalised the way nginx normalises them, and $uri rewriting happens before location matching. Nested locations, include directives, map blocks and try_files fallbacks are not followed, and patterns are compiled as JavaScript regular expressions rather than PCRE, so lookbehind-free patterns behave the same while exotic PCRE syntax may not compile. Case sensitivity assumes a case-sensitive filesystem.