Fix NGINX Location Block Precedence Prompt
Untangle why the wrong NGINX location block is matching a request by tracing prefix vs regex vs exact-match precedence, then reorder/rewrite the blocks so each URL hits the intended handler.
- Target user
- DevOps engineers debugging NGINX routing and 404/wrong-handler issues
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior NGINX engineer who understands location matching precedence cold. A request is hitting the wrong location block and I need it traced and fixed. I will provide: - All `location` blocks from the relevant `server` (paste them in file order) - The exact request URI that is misrouting and what it currently does vs what it should do - Any `try_files`, `rewrite`, `return`, or `alias`/`root` inside those blocks - The NGINX version Your job: 1. **Explain the match order** — state NGINX's actual precedence: exact `=`, then longest prefix `^~` (stops regex), then regex `~`/`~*` in file order, then plain prefix as fallback. Map my blocks onto this order. 2. **Trace the URI** — walk through which block my problem URI matches and exactly why, calling out the block that wins and the ones that are shadowed. 3. **Spot the trap** — identify common bugs: a greedy regex beating a prefix, a missing `^~`, `alias` vs `root` path confusion, or `try_files` falling through unexpectedly. 4. **Reorder/rewrite** — give corrected location blocks (and modifiers) so each URI routes correctly, preserving the others. 5. **Guard against regressions** — note which other URIs could be affected by the change and how to confirm they still route correctly. 6. **Verify** — provide curl commands per affected path and, where useful, an `error_log debug` or `add_header X-Debug-Location` technique to prove which block served the request. Output as: (a) precedence walkthrough for my URIs, (b) the bug, (c) corrected blocks, (d) verification matrix.
Related prompts
-
Secure NGINX Reverse-Proxy Vhost Prompt
Write a hardened NGINX reverse-proxy server block that forwards correct headers, hides upstream details, sets sane security headers, and avoids common proxy footguns like open host headers and missing real-IP handling.
-
Write Safe NGINX Redirect & Rewrite Rules Prompt
Author correct, loop-free NGINX redirects and rewrites that preserve query strings, use the right status code, avoid open redirects, and prefer return over rewrite where possible, with test cases.