What location matching decides
When a request arrives, nginx must choose exactly one location block to handle
it. The rules are not simply “first match wins” or “longest wins” — there is a
specific priority order that mixes modifiers (=, ^~, ~, ~*, none),
prefix length, and file order for regexes. Misunderstanding this order is
the source of countless “why is the wrong block serving my request” bugs.
How it works
nginx resolves a location in this order:
- Exact
location = /path— if it matches, stop. Highest priority. - Find the longest matching plain prefix (
location /pathandlocation ^~ /path). Remember it. - If that longest prefix used
^~, select it and skip all regex. - Otherwise evaluate regex locations (
~case-sensitive,~*case-insensitive) in file order; the first to match wins. - If no regex matches, fall back to the longest plain prefix from step 2.
So exact beats preferential prefix, which beats regex, which beats an ordinary prefix. The tester below runs this exact algorithm against any path and your set of blocks.
Tips and notes
Use = for hot single URIs like / or /favicon.ico to short-circuit matching.
Use ^~ /static/ to protect an asset directory from regex handlers. Remember
regexes are tried in the order written, so put more specific regex blocks
above general ones. A trailing slash changes the prefix, so location /api and
location /api/ match different sets of URIs — pick deliberately.