Nginx Location & Rewrite Deep Dive: 8 Priority Rules, 3 Flag Semantics, 10 Production Pitfalls
This comprehensive guide explains Nginx location matching priorities, rewrite flag semantics (last/break/redirect/permanent), and common production pitfalls through real incidents, source-code-level logic, debugging techniques, and 20 interview Q&As to help engineers avoid routing misconfigurations.
Introduction
Nginx location acts as the routing table and rewrite as its URL rewriter — together they decide where a request lands and what it looks like. Despite sounding simple, this area produces the highest configuration error rate in production: slash boundaries in prefix matching, regex priority traps, confusion between last and break, rewrite infinite loops, and 301-triggered cache disasters.
The article distills three real incidents into three lessons: (1) location matching rules must be memorized to muscle memory — intuition fails at boundaries; (2) each rewrite flag is a distinct jump instruction — mixing last and break plants landmines; (3) redirect status code choice affects browser caching and method preservation — avoid 301, use 307 for APIs.
Three Production Incidents
Incident 1: /api_v2 Also Proxied
A gateway had location /api forwarding to an order service and location /static serving local files. Adding location /api/v2 for a new service caused legacy interfaces to return 404. Root cause: location /api was placed before location /api/v2, but the real trap was the difference between /api and /api/ in "root path semantics". Prefix matching is character-level with no "path segment" concept — /api matches /apiv2, /api_upload, etc., sending them to the order service which returned 404.
Incident 2: Rewrite Infinite Loop Spikes CPU
To compatibly support old URLs, a rule rewrite ^/product/(.*)$ /p/$1 last; was added, while another location /p/ contained rewrite ^/p/(\d+)$ /product/$1 permanent;. The two rules bounced requests between each other. A single request allows at most 10 rewrites; exceeding returns 500. However, because both used last (re-match location), each iteration restarted the matching loop, causing worker CPU to hit 100% under load. Key insight: rewrite with last means "run the entire matching process again", not "go to next line".
Incident 3: One 301 Causes Login Failures
Operations permanently redirected http://api.example.com to HTTPS using rewrite ... permanent (301). Three months later, users were logged out after password changes. Browsers permanently cached the 301 (heuristic caching without Cache-Control), and 301 downgrades POST to GET. Rolling back to HTTP failed because browsers still used the cached 301 to force HTTPS, but the HTTPS certificate had expired. Lesson: 301 is the hardest status code to undo; API gateways should use 302/307 for temporary redirects, 308 for protocol upgrades.
Technical Analysis: Matching Rules & Rewrite Semantics
1.1 Location Six Syntaxes & Priority
Location supports six modifier syntaxes, priority high to low:
= exact match — stops immediately, no regex evaluated
^~ prefix match + skip regex — longest prefix wins, regex skipped
~ and ~* regex match — case-sensitive / insensitive, first match in file order wins
no-modifier prefix match — remembers longest match but continues regex; used only if no regex matches
@ named location — not used for request matching, only for internal redirects
Exact execution order is two-phase: first find longest prefix match among all prefix rules; if it has ^~ or is =, stop; otherwise test regex in file order, first match wins. Best practice: static directories and deterministic API prefixes always use ^~, leaving regex for truly fuzzy matching — predictable behavior and better performance.
1.2 Prefix Matching Slash Boundaries
location /apimatches any URI starting with the four characters /api: /api, /api/v2, /apiv2, /api_xxx all match. To match directory semantics, use location /api/ — still matches /api/ plus anything after, but not /apiv2. However, location /api/ does NOT match the bare path /api, which falls to another prefix (usually /). Two standard fixes: (1) dual-write both location /api and location /api/, with the former returning 301 to /api/ or 404; (2) enforce trailing slashes on all API paths.
1.3 Regex File-Order Trap
Regex locations match in file order — first match wins. This differs completely from prefix "longest wins". Classic failure: location ~ \.php$ before location ~ ^/special/ causes /special/test.php to always hit PHP handler. Rule: more specific regex must appear earlier. Nested locations: inner regex only evaluated after outer prefix matches — nesting doubles mental model complexity; teams often forbid nesting beyond one level.
1.4 Rewrite Four Flags True Semantics
rewrite old new [flag]flag decides what happens after rewrite:
last — stop current location's directive sequence, re-run location matching with new URI
break — stop rewriting and stay in current location; subsequent static/proxy uses current URI
redirect — return 302 temporary redirect
permanent — return 301 permanent redirect
In server block (server rewrite phase), last and break are equivalent — both continue to location matching. Most confusing: last = "start over", break = "decide here". Mnemonic: want another location to handle it → last; only rewrite file path → break. Iron law: any rewrite after a flag in the same location never executes — flag is a stop token.
1.5 $uri vs $request_uri: Rewrite Target Distinction
Both matching and rewrite operate on $uri — decoded, no query string. $request_uri is the original request line with params and encoding. Two corollaries: (1) rewrite only changes path; parameters preserved unless explicitly appended in replacement; (2) regex matches decoded characters — %20 already space, write regex against decoded form. $args can be independently rewritten: replacement string with ? discards original params; without ? auto-appends original params. This ? is the master switch for parameter handling.
1.6 if's Reputation & Safe Usage
"If is evil": if in rewrite module evaluates earlier than most directives; if containing static file directives ( root, try_files) creates semantic confusion about which location owns the directive, causing bizarre 404/502. Safe patterns: (1) inside if only write return or rewrite (both rewrite module, defined semantics); (2) for "condition + static serving" use map + variable or try_files multi-branch. if + root is a red flag; if ($host ~ ...) { rewrite ... } is acceptable.
Core Process: One Match & One Rewrite
2.1 Match-Rewrite Decision Timeline
Request flow:
T1 Execute server-block rewrite-phase directives (URI may be rewritten)
T2 Among all locations, find longest prefix match and remember it
T3 If that prefix is = or ^~, jump to T5
T4 Test regex in file order; match → use that regex location; none match → fall back to remembered prefix
T5 Enter selected location, execute its rewrite-phase directives
T6 On last, go back to T2 with new URI (max 10 rewrites total); on break or no rewrite, proceed to content phase ( try_files /static/proxy) to produce response
This explains: "Why my regex didn't fire" → longest prefix had ^~ or =; "Why two rules partially executed" → server-level and location-level rewrite are separate phases; "Why sudden 500" → 10-rewrite limit hit (error log: cycle while rewriting).
2.2 Redirect Three-State Selection
rewrite's redirect / permanent and return 301/302/307/308 are two syntaxes for same thing. Selection matrix:
302 — temporary, old browsers may downgrade POST to GET, modern mostly preserve
303 — explicit "use GET to fetch", for post-form redirect to result page
307 — temporary, strictly preserves method and body , default for API internal redirects
301 — permanent, cached long-term by browsers and search engines, use cautiously
308 — permanent + preserves method, preferred for protocol migration (HTTP→HTTPS, domain change)
Incident 3 lesson: in user-controlled environments, 301 must have explicit Cache-Control (e.g., max-age ceiling) or be avoided; 99% of API gateway redirects should be 307.
2.3 Rewrite Debugging Three Tools
rewrite_log : set error_log to notice and rewrite_log on; — every rewrite logs "old → new, flag used", making loops and mismatches obvious.
return instrumentation : temporarily replace suspicious location with return 200 "$uri | $args | $host"; to see actual variable values — 10x faster than guessing (remove before deploy).
curl precise replay : curl -H "Host: xxx" http://127.0.0.1/path?query bypasses DNS/CDN, test gateway directly; add -I for status only. Combined, these reduce rewrite ticket triage from hours to minutes.
2.4 SPA Hybrid Deployment Standard Template
Frontend SPA + backend API on same domain is the most common deployment pattern, exercising all location/rewrite knowledge. Three-rule template:
Static assets locked with ^~ ( /assets/ prefix + long Cache-Control), skipping regex overhead
API prefix exact proxy ( location /api/ + proxy_pass), never mixed with static logic
Fallback sends unknown paths to index.html , letting frontend router handle 404
Missing any rule causes distinct failures: without (1) asset requests caught by fallback returning HTML; without (2) API 404s hard to debug; without (3) refresh on any sub-page returns 404. Bake this template into team scaffolding.
2.5 error_page: Another Internal Redirect
error_page 404 = @fallback;internally redirects on error to a named location; client sees original status code ( = decides whether to rewrite status: with = new code, without keep original). Three details: (1) internal redirect creates no new network request, client unaware — fundamentally different from rewrite redirect/permanent; (2) if error_page response has body, recursive_error_pages on enables nested fallback (default one layer); (3) in separated frontend/backend, "API 404 vs page 404 separation" is standard: configure error_page per location — API returns JSON error, page returns friendly 404 HTML, no cross-contamination.
Core Source Code: Five Key Configuration Logic Pieces
Pseudo-code abstracted from ngx_http_core/rewrite modules, each corresponding to a production pitfall.
3.1 Location Matcher: Two-Phase Decision
// 1. location matcher: two-phase decision
find_location(uri):
best = null
for loc in prefix_locs: // phase one
if uri.starts(loc.prefix):
if best==null or len(loc)>len(best):
best = loc
if best.type == EQUAL: // = hit stops
return best
if best.type == CARET: // ^~ skips regex
return best
for rx in regex_locs: // phase two sequential
if rx.match(uri): return rx
return best // fall back longest prefixThis implements 1.1. The two for-loop order and exit conditions are the entire semantics: regex is an ordered list in config, prefix is an unordered set taking longest — treating the ordered list as a set (hoping "more specific later overrides earlier") is a high-accident pattern.
3.2 Rewrite Executor: 10-Limit & Flags
// 2. rewrite executor: 10 limit & flags
apply_rewrite(r, old, new, flag):
if ++r.rewrite_count > 10:
log("cycle while rewriting")
return HTTP_500
r.uri = regsub(old, new, r.uri)
if flag == LAST:
r.phase = SERVER_REWRITE // re-match
return REDO_MATCH
if flag == BREAK:
r.phase = CONTENT // decide here
return STOP_RULES
if flag in (REDIR, PERM):
r.loc = null // direct external jump
return (flag==REDIR ? 302 : 301)Shows four flag branch behaviors. Counter is per-request: last triggers REDO_MATCH re-entering location matching; when rules form a loop the counter is the only fuse — explains why Incident 2 wasn't infinite CPU spin but 500, yet each request still burns 10 match rounds, multiplying CPU.
3.3 try_files: Content Phase Multi-Branch
// 3. try_files: content phase multi-branch
try_files(f1, f2, ..., fallback):
for f in (f1..fn-1):
path = root + f // no encoding concatenation
if exists(path) and is_file(path):
return serve(path)
// all missing → fallback
return internal_redirect(fallback)
// NOTE: last param is "internal redirect"
// not file path; /index.php re-matches location,
// =404 returns status directlyClose relative of rewrite. Last parameter semantics completely differ from first N-1 : earlier are "file probes relative to root", last is internal redirect target ( @named, =code, or URI to re-match). SPA standard try_files $uri $uri/ /index.html; works because /index.html re-matches location; writing try_files $uri /index.html; with index.html outside root yields 404/500.
3.4 root vs alias Path Concatenation Difference
// 4. root vs alias path concatenation difference
// location /img/ { root /data; }
// /img/a.png -> /data/img/a.png
// root: full uri appended after root
// location /img/ { alias /data/; }
// /img/a.png -> /data/a.png
// alias: strip location prefix then append
// Two high-frequency pits:
// 1. alias must end with /, else produces
// misaligned paths like /dataa.png
// 2. alias + regex location: regex
// captures must be explicitly referenced in alias replacementroot = "root + full path", alias = "replace prefix" — one char difference, one directory level off. Production advice: prefer root (simpler semantics, fewer errors); if alias needed, enforce trailing slash in team lint and CI — missing slash 404 is insidious because path looks "off by one character".
3.5 Health-Check Script: Matching Rule Self-Test
// 5. health-check script: matching rule self-test
# 1) Verify priority: test real URLs
for p in /api /api/ /apiv2 /api/x:
curl -s -o /dev/null -w "%{http_code}"
http://gw.test$p
# 2) Catch rewrite loop hazards
grep -n "rewrite" nginx.conf \
| grep "last" # walk each through T1-T6
# 3) Rewrite debug switch (temporary)
error_log logs/error.log notice;
rewrite_log on;
# Observe error.log for "rewritten data"Copy into ops toolbox. Matching rules must be validated with real URL boundary values (bare path, trailing slash, adjacent prefix, regex boundaries — each gets a curl). These four test cases are Incident 1's standard regression suite. rewrite_log is the first switch for debugging rewrite chains; enabled, every rewrite appears in error.log; combined with curl boundary replay, most routing issues located in under ten minutes.
Advanced Topics: Five Accounts to Settle Upfront
4.1 Routing Table Organization Standards
Gateways exceeding 30 location entries need standards or mental model collapses. Four recommendations: (1) prefix section first, regex section after, separated by comment wall; (2) regex ordered "specific to broad" with business ownership comments; (3) prefixes always carry semantic boundary ( /api/ not /api), bare path in /api returns 308 to /api/; (4) each location tail comment: "validation URL + expected status code", CI runs these as regression. Turns routing table from "art" into "testable code" — highest ROI accident prevention.
4.2 map: 10x More Elegant Variable Calculator Than if
For "choose variable based on another variable" (pick backend by domain, version by UA), map is the answer: map $http_user_agent $is_mobile { default 0; ~*mobile 1; } then use if ($is_mobile) or variable routing in location. map evaluates at config load, computes once per request, no execution-order traps ; supports hostnames and combined defaults. Converting all team if to map + return typically eliminates half of weird routing bugs — solution to "if is evil" isn't fewer conditions, it's moving conditions into map.
// map + variable routing: standard posture to kill if
map $http_user_agent $is_mobile {
default "desktop";
~*mobile "mobile";
}
map $host $backend {
hostnames; // wildcard domain support
api.a.com api_pool;
*.a.com web_pool;
default web_pool;
}
location / {
proxy_pass http://$backend;
// route by UA/domain, no execution-order traps
}4.3 Rewrite Performance Accounting
Single rewrite is nanoseconds, but three amplifiers stack: (1) regex backtracking — location regex and rewrite regex each run once; catastrophic backtracking patterns (nested quantifiers .*.*) make single-request CPU milliseconds; (2) last re-match — each last adds a full location match round; hot paths should prefer break or exact routing; (3) if chains — every if evaluates early in request; dozens of if show up in load-test curves. Baseline action: before gateway config lands, run wrk against "coldest route" (path hitting most rewrites); if P99 vs hottest path exceeds 20%, optimize rules not add machines.
4.4 Migration-Period Compatible Routing Design
Legacy URL migration tests rewrite design most. Three-step method: (1) dual routing coexist — old and new paths point to same backend, rewrite only does "transparent normalization" (old → new via break or internal redirect), user unaware; (2) observation period collect data — access log tracks legacy path residual traffic, proceed when below 1%; (3) external references last — after confirming search engine and external link scale, upgrade old path to 301 (or 308 preserving method). Anti-pattern: immediate 301 — traffic data lost, rollback locked by browser cache, turning "reversible migration" into "irreversible gamble".
4.5 Three High-Frequency Ops Pitfalls
Missing rewrite flag — no flag equals last but only in location; in server block semantics differ subtly — flag must be explicit.
Chinese chars and spaces in regex — URI already decoded; matching Chinese paths requires quoted regex and attention to Nginx version UTF-8 handling differences; prefer ASCII paths.
Variable used before set — rewrite replacement references $var from map / if but branch not taken → empty string → double-slash paths like //x causing upstream 404. Common root cause: "rewrite is sequential instruction stream, not declarative rules" — read config with instruction-stream mindset, pits become visible.
Learning Path: From Usage to Mastery
Step 1, memorize two tables : six location syntax priority table + four rewrite flag semantics table — this domain's multiplication table. Step 2, build local range : one Nginx container with five intertwined rules (exact/prefix/^~/regex/named), verify 1.1 conclusions with curl boundary values, enable rewrite_log to observe rewrite chains. Step 3, read two sources : official ngx_http_rewrite_module directive examples, and community classic "If is Evil" — focus not on conclusions but understanding "which location owns this directive" evaluation model. Step 4, run one production drill : add "validation URL test suite" to your gateway config and wire into CI; turn this article's five source-code skeletons into review checklist. After these four steps, location/rewrite tickets in your hands should only be new requirements and misoperations, not mysticism.
High-Frequency Interview Questions (with Answers)
Twenty Q&A pairs covering: six location syntaxes, /api vs /api/, regex priority, last vs break, rewrite 500 cause, 301/302/307/308 selection, "if is evil" and safe use, $uri vs $request_uri, rewrite replacement ? behavior, try_files last param specialness, root vs alias, ^~ purpose, nested location rules/risks, named location ( @name) use cases, map vs if advantages, flag-stopped rewrite execution, rewrite regex matching decoded vs encoded, debugging non-firing rewrite, legacy URL migration routing design, large gateway location config loss prevention.
One-Page Cheat Sheet
Match : = instant stop → longest prefix ( ^~ locks) → regex file order → fallback prefix. Prefix is char-level; directory semantics add slash.
Rewrite : last restart, break decide here, redirect / permanent external jump; rewrites after flag all dead; per-request limit 10.
Redirect : API use 307, migration use 308, 301 cautious (browser permanent cache).
Params : rewrite leaves $args alone; replacement with ? drops original params.
Condition : if only return / rewrite; selection logic into map.
Static : root appends full path, alias replaces prefix must have trailing slash; try_files last param is internal redirect.
Summary & Next Episode Preview
All location/rewrite difficulty compresses to one cognition: Nginx config is an instruction stream, not declarative rules — matching has two phases, rewrite executes sequentially, flags are stop tokens . Burn the two-phase match, four flags, 10-limit, ? param switch into muscle memory; turn validation URL test suite into CI regression; routing accidents transform from mysticism into locatable engineering problems. Next episode enters traffic core: reverse proxy & load balancing — proxy_pass five syntaxes, upstream scheduling algorithms & passive health checks, and "proxy path concatenation" — another slash hell.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
