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.
- Target user
- DevOps engineers handling migrations, canonicalization, and URL changes in NGINX
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior NGINX engineer who writes redirect and rewrite rules that don't loop, leak, or break SEO. I need correct rules for a URL change. I will provide: - The mapping I want (old → new): host canonicalization, http→https, trailing-slash policy, path moves, or a bulk old-path table - Whether redirects must be permanent (301/308) or temporary (302/307), and whether request method/body must be preserved - Existing `server`/`location` blocks and any current rewrite/return rules - Whether this fronts an app that also does its own redirects (loop risk) Your job: 1. **Pick the mechanism** — prefer `return 301 https://...$request_uri` and dedicated `server` blocks over regex `rewrite` for canonical/host redirects; reserve `rewrite ... last/break` for genuine internal path rewriting. 2. **Choose the status** — 301 vs 308 (method-preserving) and 302 vs 307, and explain caching/SEO implications of getting it wrong. 3. **Preserve correctly** — keep the query string (`$request_uri` vs `$uri`+`$args`) and avoid double-encoding; handle trailing slash consistently. 4. **Prevent loops & open redirects** — ensure http→https and host canonicalization can't ping-pong, and never build a redirect target from untrusted Host/`$arg_` input. 5. **Order & context** — place rules so they don't shadow each other or fight `try_files`, and use `merge_slashes`/`$request_uri` carefully. 6. **Verify** — give `curl -I` test cases for each mapping (with and without query string, http and https, www and apex) showing the exact Location and status. Output as: (a) the redirect/rewrite config, (b) why this mechanism and status, (c) loop/open-redirect check, (d) curl test matrix.
Related prompts
-
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.
-
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.