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.

Server configuration and request

one block per location [modifier] pattern {; bodies can be empty, braces on the next line are fine

the path, query string ignored

Only the block headers are read, never the directives inside them; the answer is about which block runs, not what it does.

Matched block

nginx would hand this request to—

Match kind
—
Longest prefix
—
Blocks read
—
—

    Every block, in file order, and how far it got in the search
    LocationLineOutcome

    The order nginx searches

    1. Exact match first. A block written location = /path is compared literally against the request path; if it is equal the search ends there, whatever else is configured.
    2. 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 /api also matches /apiary, which is why trailing slashes are worth writing deliberately.
    3. ^~ 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.
    4. 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.
    5. 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_files or error page sends the request elsewhere.
    6. Named locations are not candidates. A block named @fallback can only be reached by an explicit reference such as try_files … @fallback or error_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.