Developer Utility

Nginx Redirect Generator

Quickly build error-free Nginx URL redirect rules, location blocks, rewrite patterns, and SSL/WWW forcing configurations.

Backend engineers, system administrators, and SEO professionals configure web servers to route traffic correctly. When to use it: When moving to a new domain, reorganizing directory folders, updating page URLs, forcing secure HTTPS, or blocking crawler access to private resources. What it solves: It eliminates server configuration bugs and formatting errors by providing visual controls that convert paths into valid server block codes. Why it matters: Broken Nginx syntax will prevent the server from starting or create endless redirect loops, destroying search indexation and site availability.

⚙️ Redirection Rules

Matched URL path. For Location blocks, standard path is evaluated.

Target redirect location. Can be absolute or relative path.

📋 Config Snippet

💡 Deployment: Place this code block inside the active server { ... } container of your Nginx site configuration file (typically in /etc/nginx/sites-available/).

How Nginx Redirections Work

Nginx evaluates inbound HTTP headers and maps the requests to active server configurations using server_name filters. When matching routes within a server container, it parses location rules first, proceeding sequentially or prioritizing exact matches based on matching prefix symbols.

If Nginx encounters a return directive inside a location container, it immediately halts request processing and returns the configured HTTP status code (e.g. 301 Moved Permanently) along with the destination header back to the client. This bypasses further processing pipelines, making it extremely CPU-efficient.

For regex match rules (rewrite), Nginx uses a PCRE regular expression library to match path string components. Capture variables (e.g. $1) are extracted and bound to variables, letting the router rewrite paths dynamically before triggering the redirect block.

Before / After Redirect Rules

Scenario: Redirecting Legacy Blog Subfolder

❌ Before (Inefficient Regex Rule)

rewrite ^/blog/(.*)$ https://newsite.com/blog/$1 permanent;
 

✅ After (Optimized Prefix Location block)

location /blog/ {
    return 301 https://newsite.com$request_uri;
}
 

Nginx Redirect Use Cases

Developer Production Workflow
Translate Apache .htaccess rules to Nginx server block files during migrations Enforce sitewide HTTPS SSL and www/non-www URL resolution rules Maintain page rankings during major database and URL restructures
Write rewrite directives to map dynamic REST APIs to static paths Shield sensitive git or deployment credentials from public requests Redirect legacy image folders to cloud-hosted storage endpoints

Common Nginx Redirect Mistakes & Troubleshooting

Redirect Loop (Infinite redirection loops)

If your target destination matches the rewrite source pattern, Nginx will continuously redirect visitors to the same block until the browser aborts. Ensure source paths differ from final destinations, or use strict = exact match location tags.

Omiting semi-colons (;) at end of lines

Every Nginx configuration line must end with a semi-colon. Leaving these off will trigger critical configuration test failures and crash the Nginx service.

❌ return 301 /new-page
✅ return 301 /new-page;

Mixing Rewrite Flags

Ensure you specify permanent (301) or redirect (302) flags at the end of rewrite rules. Failing to do so causes Nginx to perform an internal rewrite, altering the path silently without informing the user's browser via a redirect.

Best Practices

Prefer return over rewrite

Whenever possible, use the simple return 301 directive. It is easier to write, less error-prone, and faster to compile inside the Nginx core thread.

Always Validate configs

Run sudo nginx -t in the terminal to verify config integrity before applying reload signals. A single configuration typo can take your entire site offline.

Use $request_uri to preserve paths

Utilize the Nginx system variable $request_uri to map subpaths and query strings automatically to new domains without creating multiple rules.

Group redirect server blocks

Isolate redirection server blocks from active web application blocks. Keeping separate files in sites-enabled makes troubleshooting and cleanup easy.

Frequently Asked Questions

What is the difference between "return" and "rewrite" in Nginx? +

Nginx supports two primary methods for URL redirection: the "return" directive and the "rewrite" directive. The "return" directive is simpler, faster, and highly recommended for simple domain-level or path-level redirects (e.g., return 301 https://example.com$request_uri;). The "rewrite" directive, on the other hand, is a more powerful regex-based parser used when you need to match complex URL query parameters, capture subpatterns, or modify paths before passing them downstream. In terms of server performance, "return" is preferred because Nginx stops processing the block immediately once matched.

How do I redirect an entire site to a new domain using Nginx? +

To redirect all incoming traffic from an old domain to a new domain, place a return directive inside your Nginx server block. Use the code: `return 301 $scheme://newdomain.com$request_uri;`. This syntax captures the request protocol (HTTP or HTTPS) and the exact path query parameters, passing them cleanly to the new domain. Make sure this directive is placed within a server block that is listening on port 80 and/or 443 with the server_name set to your old domain.

Should I use a 301 or 302 status code for Nginx redirects? +

Use a 301 redirect (Moved Permanently) for permanent site migrations, URL structure updates, or domain transfers. A 301 redirect passes roughly 95-99% of ranking authority (link equity) to the new destination page, signaling search engines to update their indexes. Use a 302 redirect (Moved Temporarily) only for short-term changes, such as running seasonal promotions, performing site maintenance, or A/B testing layouts, which tells search engines to keep indexing the original URL.

What is a trailing slash redirect and how do I enforce it in Nginx? +

A trailing slash redirect ensures that URLs resolve consistently (e.g., redirecting /blog to /blog/). Inconsistent trailing slashes can create duplicate content issues where Google indexes both versions separately. You can enforce a trailing slash in Nginx by adding a rewrite rule: `rewrite ^([^.?]*[^/])$ $1/ permanent;`. This rule matches any URL path that does not contain a file extension or a trailing slash, and appends a slash before executing a 301 redirect.

How does location block matching precedence work in Nginx? +

Nginx evaluates location blocks based on a strict matching precedence hierarchy: first, it checks for exact matches using the `=` modifier; second, it checks for preferential prefix matches using the `^~` modifier; third, it evaluates regex matches using `~` (case-sensitive) or `~*` (case-insensitive); and finally, it falls back to standard prefix matches (e.g., `location /`). Once Nginx finds a match in a higher priority group, it stops checking subsequent blocks. Our generator lets you choose these matching types to ensure your redirects fire in the correct order.

How do I test my Nginx redirect configurations for errors? +

Before reloading your live Nginx server, always validate your configuration files for syntax mistakes by running the terminal command: `sudo nginx -t`. This command checks all active config files, testing locations, rewrites, and file inclusions for compile errors. If the test passes with "syntax is ok" and "test is successful", you can safely apply the new rules by running `sudo systemctl reload nginx` or `nginx -s reload` without causing downtime.

Can Nginx redirects handle URL query parameters? +

Yes, Nginx handles query parameters differently depending on the directive. The "return" directive automatically appends the incoming query string to the destination URL. For the "rewrite" directive, Nginx appends the query string by default; if you want to discard the query parameters in a rewrite rule, you must append a question mark at the end of the destination path (e.g., `rewrite ^/old-path$ /new-path? permanent;`).