Debugging Nginx Location Block Matching Precedence
Master Nginx location evaluation rules across exact matches, ^~ prefix priority, regex ordering, and internal rewrites without unexpected fallthroughs.
On this page
Why Nginx Location Rules Surprise Developers
Few configuration mechanisms generate as many subtle production outages as Nginx location matching. A developer adds location ~* \.(js|css|png)$ at the bottom of a server block to attach long-lived Cache-Control headers to static files, and suddenly authenticated proxy endpoints like /api/users/avatar.png or /graphql/playground.js begin returning 404 Not Found from disk instead of hitting the upstream backend.
The root cause is that Nginx does not simply read location directives from top to bottom like an Express router. Instead, Nginx executes a deterministic multi-stage algorithm that mixes longest-prefix selection (order-independent) with first-match regular expression scanning (strictly top-down order-dependent), plus explicit short-circuit modifiers (= and ^~). Once you internalize the exact decision tree, every routing surprise becomes completely predictable.
The Exact Four-Stage Location Resolution Algorithm
Whenever Nginx routes a normalized request URI (stripped of query string and decoded of %XX escapes and .. segments), it evaluates candidate location blocks inside the matching server in four fixed stages:
- Exact match (
location = /path): Nginx checks all=blocks. If an exact byte-for-byte match exists, search terminates immediately and that block wins—even if regex blocks or longer prefixes exist. This makeslocation = /andlocation = /healthzboth unambiguous and extremely fast. - Longest prefix match (
location /prefixorlocation ^~ /prefix): Nginx inspects every non-regex prefix block and remembers the single longest prefix that matches the start of the URI. File declaration order plays zero role here. If the longest matching prefix block happens to use the^~modifier, Nginx stops immediately and selects it without testing any regexes. - First regex match (
location ~andlocation ~*): Only if the longest prefix block did not carry^~, Nginx evaluates all regular expression locations in the exact top-to-bottom order written in the config file (~for case-sensitive PCRE,~*for case-insensitive). The first matching regex wins immediately, overriding the remembered prefix block from stage 2. - Fallback to remembered prefix: If zero regex blocks match, Nginx falls back to the longest prefix block saved during stage 2.
You can trace every step of this algorithm against your own config snippets and see which block wins and why in the Interactive Nginx Location Tester.
Avoiding Regex Shadowing and Proxy URI Pitfalls
Look at a realistic configuration combining static asset caching, an API upstream, an admin panel, and an exact health endpoint. Notice how ^~ protects /api/ from extension regexes, while location = /healthz bypasses overhead altogether.
server {
listen 80;
server_name app.example.com;
root /var/www/app;
# Stage 1 winner: exact match terminates search immediately
location = /healthz {
access_log off;
return 200 "ok\n";
}
# Stage 2 short-circuit (^~): protects /api/* paths even if URI ends in .json or .png
location ^~ /api/ {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Trailing slash strips /api/ prefix -> upstream receives /orders
proxy_pass http://api_backend/;
}
# Stage 2 fallback prefix if no regex matches
location / {
try_files $uri $uri/ /index.html;
}
# Stage 3 regex: matches static files NOT under /api/ or /healthz
location ~* \.(?:css|js|woff2|png|svg)$ {
expires 30d;
add_header Cache-Control "public, immutable" always;
try_files $uri =404;
}
}
Pay particular attention to two subtle details in the snippet above. First, notice proxy_pass http://api_backend/; has a trailing slash /, whereas proxy_pass http://api_backend; does not. With a URI path (even a bare /), Nginx replaces the matched prefix /api/ with /, turning /api/v1/users into /v1/users. Omitting the trailing slash forwards /api/v1/users unchanged. Note also that inside regex locations (~), proxy_pass cannot contain a URI path unless you rewrite $request_uri explicitly with rewrite.
Second, remember that try_files ... /index.html performs an internal redirect when it reaches its final fallback parameter. Once Nginx switches internally to /index.html, the entire four-stage location lookup runs a second time for /index.html, meaning your location / or location = /index.html headers govern the final response—not any temporary headers from the first pass.
Nested Locations, Trailing Slashes, and if Traps
Several Nginx idioms cause silent regressions when combined with location matching:
- Regex order inversion: Placing a broad regex like
location ~* \.(json|xml)$above a specific regexlocation ~ ^/webhooks/.*\.json$causes the broad block to shadow the specific one forever. Order regexes from most specific to most general, or isolate prefixes with^~. - Missing trailing slash in prefix vs URI:
location /docsmatches/docs,/docs/, and/docs-legacy! If you only intend to route a directory subtree, writelocation /docs/(or pairlocation = /docswithlocation /docs/), otherwise/docs-v2leaks into the wrong upstream. - Repeated
add_headerloss across blocks: Nginx inheritsadd_headerdirectives fromserverintolocationonly if the winninglocationdeclares zeroadd_headerlines of its own. The moment you write oneadd_header Cache-Controlinside your regex asset block, security headers (X-Content-Type-Options,Strict-Transport-Security) declared atserverlevel disappear from those responses. - Unintended
ifblocks insidelocation: Usingifinsidelocationfor anything other thanreturnorrewrite ... lastalters location inheritance unpredictably (“If Is Evil” in Nginx docs). Prefermapblocks at thehttplevel whenever you need conditional header values or upstream routing. - Regex capture groups wiped by a later regex: Any
rewrite,if ($http_user_agent ~ ...), orlocation ~match overwrites numeric captures$1and$2immediately. Always use named captures ((?<slug>[^/]+)) when values cross directive boundaries.
Testing Location Matches Before Reloading
Never reload production Nginx purely on faith after refactoring location rules. First, run the candidate location blocks against representative test paths—including edge URLs like /api/export.csv, /api/avatar.png, /, /docs-old, and /assets/app.JS (uppercase extension)—inside the Interactive Nginx Location Tester. Remember to test URL-encoded path segments too (such as /api/files%2Freport.png), because Nginx decodes percent escapes before evaluating location rules while forwarding normalized paths upstream.
# Validate syntax and merged effective config before reload
sudo nginx -t
# Verify exact upstream routing in staging with temporary trace header
curl -i "https://staging.example.com/api/avatar.png"
curl -i "https://staging.example.com/assets/app.js"
curl -i "https://staging.example.com/healthz"
In staging environments (never leak internal block names in public production headers unless intended), temporarily adding a diagnostic header or inspecting access logs with $request_uri and $upstream_addr confirms that ^~, =, and regex blocks resolve identically under real HTTP traffic. Also test HEAD and POST methods against static and proxy locations, because static-file handlers reject POST with 405 Not Allowed whenever an API route accidentally falls into a static root prefix.
FAQ
- Does declaration order matter for Nginx prefix location blocks?
- No. For plain prefix locations and ^~ prefix locations, Nginx always selects the longest matching prefix regardless of where it appears in the file. Declaration order only controls regex locations (~ and ~*), where the very first regex match wins.
- Why did my ^~ /static/ block skip a regex location that matched the file extension?
- That is the exact purpose of ^~: if the longest matching prefix carries the ^~ modifier, Nginx stops immediately after prefix matching and skips all ~ and ~* regular expression evaluations.
- Why does adding a trailing slash to proxy_pass change the upstream URI?
- When proxy_pass http://upstream; has no URI component, Nginx forwards the original request URI verbatim. Adding a trailing slash—proxy_pass http://upstream/;—makes Nginx replace the matched location prefix with / before forwarding.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.