Nginx Rewrite Rule Generator
Visually build Nginx rewrite and redirect rules. Configure regex path matches, permanent 301/302 redirects, and conditional server checks. 100% client-side, zero data uploads.
🔧 Rule Configuration
❓ Conditional Check (if block)
How ZeroData protects your privacy
- ✓ No Uploads: Processing happens entirely via client-side JavaScript.
- ✓ No Storage: We do not have a database. We physically cannot save your data.
- ✓ No Tracking: We don't log what you process or track your inputs.
- ✓ Verifiable: Check your DevTools Network tab. You will see 0 outbound requests.
What Are Nginx Rewrite Rules and Why Do They Matter?
Nginx rewrite rules are server-side directives that intercept incoming HTTP requests and transform the URI before the web server decides how to handle them. They are one of the most powerful features in Nginx configuration, enabling everything from simple page redirects to complex URL rewriting logic using Perl-compatible regular expressions (PCRE).
Whether you are migrating a legacy PHP application to a modern framework, consolidating multiple domains, or enforcing HTTPS across your entire site, rewrite rules are the mechanism that keeps your links working and your SEO rankings intact during the transition.
Understanding Core Nginx Directives
- Rewrite (
rewrite pattern replacement [flag]): Modifies the client's request URI according to regular expressions. Supports internal parsing loops or browser redirects. Evaluated top-to-bottom within aserverorlocationblock. - Return (
return code [text/url]): Returns an immediate HTTP status directly to the browser (such as 301, 302, 403, or 500). Nginx documentation recommendsreturnoverrewritefor simple redirects because it skips regex execution blocks for maximum throughput. - Redirect Flags:
permanentreturns HTTP 301, instructing search engines and browsers to permanently cache the new URL and transfer link equity.redirectreturns HTTP 302, used for temporary migrations where the original URL may return.laststops rewrite processing and forces Nginx to scan for a new matchinglocationblock with the modified URI.breakstops rewrite processing and serves content from the current location block without starting a new location search.
Capture Groups and Dynamic URL Rewriting
Nginx rewrite rules support PCRE capture groups. Enclose sub-expressions in parentheses in your match pattern (e.g., ^/blog/(.*)$), then reference them as $1, $2, etc. in the destination string. This enables powerful wildcard redirects — for example, redirecting an entire legacy blog directory to a new path while preserving all post slugs: rewrite ^/blog/(.*)$ /articles/$1 permanent;
Common Nginx Rewrite Pitfalls & Production Mistakes
Nginx configuration syntax is notoriously unforgiving. A single misplaced character can cause redirect loops or prevent the server from restarting. Below is a troubleshooting table of frequent Nginx rewrite errors and how to fix them:
| Mistake / Anti-Pattern | Why It Breaks Production | Correct Approach |
|---|---|---|
| Missing semicolon (;) | Nginx directives must terminate with a semicolon. Omitting it causes a fatal syntax error during startup or reload. | Always check that every directive line ends with ; before running nginx -t. |
| Unescaped dots in regex | Writing example.com in a regex matches ANY character in place of the dot (e.g., example-com or exampleXcom). | Escape literal periods with a backslash: example\.com. |
| Infinite redirect loops | Rewriting ^/page to /page/new without anchoring or flags causes the target URI to match the rule again in an endless cycle. | Use strict regex boundaries like dollar signs (^/page$) or terminating flags (break / permanent). |
| Using rewrite vs return | Using rewrite ^ https://$host$request_uri? permanent; forces Nginx to compile and evaluate regex engine checks unnecessarily. | Use return 301 https://$host$request_uri; for simple domain or protocol redirects for maximum performance. |
| Nested if blocks | Nginx architecture does not support nested conditional blocks. Attempting to nest conditionals leads to unexpected directive evaluation ("if is evil"). | Use flat single-level conditionals or combine matching logic using standard regex compound statements. |
Actionable Terminal Commands for Nginx Debugging
When applying new rewrite rules or diagnosing redirect chains on your Linux server, use these essential command-line tools:
- Validate configuration file syntax before restarting Nginx:
sudo nginx -t
Parses all configuration files and reports syntax errors, missing semicolons, or invalid regex without disrupting live traffic. - Reload Nginx configuration gracefully without dropping active connections:
sudo systemctl reload nginx
Alternatively, usesudo nginx -s reloadto send a SIGHUP signal directly to the master process. - Inspect HTTP redirect response headers without fetching page bodies:
curl -I https://example.com/old-path
Verifies whether your server returns a 301 Permanent or 302 Temporary status code and checks the exact target in theLocationheader. - Follow redirect chains and view all intermediate hops:
curl -iL https://example.com/old-path
Helps identify redundant redirect hops (e.g., HTTP → HTTPS → WWW → New Path) that degrade SEO crawl budget and page load speed. - Monitor Nginx error logs in real time for rewrite processing failures:
tail -f /var/log/nginx/error.log
When Should I Use This? vs When Should I NOT Use This?
✅ When You SHOULD Use This Tool
- Restructuring website URL hierarchies during CMS migrations or domain consolidations.
- Enforcing HTTPS by permanently redirecting unencrypted HTTP port 80 traffic to port 443.
- Canonicalizing hostnames by forwarding non-www domains to www (or vice versa) for consistent SEO.
- Blocking malicious bots, scrapers, or deprecated client apps using User-Agent conditionals.
❌ When You Should NOT Use This Tool
- Serving static files from alternate directory structures (use Nginx
aliasorrootdirectives instead). - Routing traffic to application servers or backend APIs (configure
proxy_passwithin location blocks). - Implementing rate limiting, DDoS mitigation, or CORS access control policies (use dedicated Nginx security modules).
Browser Compatibility & Zero-Upload Privacy Notice
Our Nginx Rewrite Generator compiles and validates your configuration rules entirely within your web browser using client-side JavaScript. No domain names, internal URL routing maps, legacy migration schemas, or infrastructure security policies are ever sent over network requests or logged by external servers.
This zero-upload guarantee ensures complete privacy when planning enterprise server migrations or restructuring confidential intranet endpoints. The generator operates seamlessly offline and is fully compatible with all modern desktop and mobile browsers (Chrome, Firefox, Safari, Edge) without relying on backend API calls.
Related Security & Nginx Infrastructure Tools (Authority Triangle)
Building secure, high-performance web servers requires more than just clean rewrite rules. Explore our interconnected infrastructure tools to harden your server environment:
- CORS Header Generator — Build Cross-Origin Resource Sharing rules and
add_header Access-Control-Allow-Origindirectives for Nginx API servers. - Security Headers Builder — Generate critical HTTP security headers including Content-Security-Policy (CSP), HSTS, X-Frame-Options, and X-Content-Type-Options.
- Nginx Config Generator — Generate complete, production-ready Nginx server block files with SSL/TLS best practices, gzip compression, and HTTP/2 support.
- Nginx Rate Limiting Configurator — Protect your endpoints from DDoS attacks and brute-force scraping using custom
limit_req_zoneand burst configurations. - Regex Tester & Debugger — Verify and troubleshoot complex PCRE capture groups before deploying them in Nginx rewrite rules.
For end-to-end server security guidance, read our Web Security Complete Guide.
How to Use the Nginx Rewrite Rule Generator
- Select a configuration template or choose 'Custom Redirect / Rewrite'.
- Enter the incoming URL pattern/regex and the target destination path.
- Select the redirect type (301 Permanent, 302 Temporary, or internal Nginx rewrites like Last/Break).
- Optionally enable case-insensitive matching using the ~* operator.
- Add an optional conditional 'if' block to match on variables like $host or $scheme.
- Copy the generated block and paste it directly into your server block config.
- Run 'sudo nginx -t' to verify syntax, then reload Nginx.
Common Use Cases
- Enforcing HTTPS by redirecting all HTTP requests to secure SSL connections.
- Redirecting traffic from www to non-www domains (or vice versa) for consistent domain SEO.
- Mapping legacy website URLs to a new directory hierarchy using regex variables.
- Securing sensitive config folders by returning immediate 403 Forbidden statuses.
- Performing wildcard redirects after restructuring a website's URL hierarchy.
- Blocking crawlers or bots by matching on the $http_user_agent variable.
Frequently Asked Questions
What is an Nginx rewrite rule?
An Nginx rewrite rule is a directive that changes the request URI using regular expressions. It allows you to redirect old URLs to new ones, mask real internal file structures, or enforce SEO-friendly URL patterns without exposing the backend directories.
What is the difference between 'return' and 'rewrite' in Nginx?
The 'return' directive is simpler and faster because it stops processing immediately and sends a status code (like 301 or 302) or text to the client. The 'rewrite' directive is more complex; it uses regular expressions to modify the URI internally and can either perform a redirect or pass the modified URI further down the server configuration.
What do the flags 'last', 'break', 'redirect', and 'permanent' mean?
1) 'last' stops processing the current rewrite directives and starts a new search for a matching location block with the rewritten URI. 2) 'break' stops processing rewrite directives but continues executing within the current location block. 3) 'redirect' returns a temporary 302 redirect to the browser. 4) 'permanent' returns a permanent 301 redirect.
Are my redirect rules processed on your server?
No. All configuration logic and text generation happen 100% in your browser. No domains, redirect paths, or regex strings are ever uploaded or transmitted.
Where do I paste the generated rules in my Nginx config?
You typically paste these rules inside a 'server' block or a specific 'location' block within your Nginx virtual host configuration file (usually found in /etc/nginx/sites-available/). Remember to run 'nginx -t' to test the syntax before reloading Nginx.
Can Nginx rewrite rules use capture groups?
Yes. In the match pattern, wrap sub-expressions in parentheses (e.g. ^/old/(.*) ) and reference them in the destination as $1, $2, etc. For example: rewrite ^/blog/(.*)$ /posts/$1 permanent; moves all blog posts to the /posts/ path.
How do I test my Nginx configuration before applying it?
After pasting your generated rules into the config file, always run 'sudo nginx -t' to validate the syntax. If the test passes, reload the service with 'sudo systemctl reload nginx' or 'sudo nginx -s reload'.
Related Tools
CORS Header Generator
Generate CORS headers for Nginx, Apache, and Express.js with a visual builder. No data uploaded.
Systemd Service Generator
Generate Linux systemd service unit files visually. Configure ExecStart, restart policies, and dependencies — 100% browser-based.
Nginx Config Generator
Generate Nginx server block configurations visually. Reverse proxy, SSL, gzip, and security headers — 100% browser-based.
Nginx Rate Limiting Configurator
Generate Nginx rate limiting directives visually. Configure limit_req_zone, burst, nodelay, and custom 429 error pages — 100% browser-based.