Developer Tools

Free Nginx Redirect Generator Online

Generate Nginx redirect rules with return, rewrite or location blocks. Supports 301/302/307/308, domain matching, query string handling and regex patterns.

Nginx Redirect Configuration: A Complete Guide

Nginx handles millions of redirects per second across the web — from enforcing HTTPS to migrating entire domains. Getting redirect configuration right is critical for both SEO (search engines need correct status codes to transfer link equity) and user experience (broken redirects mean lost visitors). This tool generates production-ready Nginx redirect configurations from simple inputs, so you can focus on what goes where rather than on syntax.

When to Use Each Redirect Status Code

HTTP defines four redirect status codes, each with different semantics. Choosing the wrong one can hurt SEO or break API clients.

  • 301 Moved Permanently: The canonical choice for permanent URL changes — domain migrations, slug restructures, HTTP→HTTPS. Browsers and proxies cache 301s aggressively, and search engines transfer ~90–99% of link equity to the target URL. Use this when the old URL will never come back.
  • 302 Found (Temporary): Tells browsers and search engines that the original URL is still the canonical one. Use for A/B tests, geo-routing, maintenance pages, or any redirect you plan to remove. Note: some older clients change POST to GET on 302.
  • 307 Temporary Redirect: Like 302 but guarantees the HTTP method is preserved — a POST request stays a POST. Use for API endpoints or form submissions that are temporarily relocated.
  • 308 Permanent Redirect: Like 301 but preserves the HTTP method. Use for API endpoints that have permanently moved but must continue to accept POST/PUT/DELETE requests. Relatively new (RFC 7538, 2015) — older HTTP/1.0 clients may not understand it.

Three Ways to Redirect in Nginx

Nginx offers three mechanisms for redirects. They differ in flexibility and performance:

return — Fastest and Simplest

location = /old-page {
    return 301 /new-page;
}

The return directive is processed immediately — Nginx does not evaluate any regular expressions or walk the location tree further. It is the fastest redirect method and should be your default choice for exact-path redirects. It can be placed at the server level (applies to all URIs) or inside a location block.

rewrite — Pattern Matching with Regex

rewrite ^/blog/(.*)$ /articles/$1 permanent;

The rewrite directive evaluates a PCRE regular expression against the URI. Use it when you need to capture parts of the old URL and insert them into the new URL — for example, redirecting an entire directory while preserving the slug. The permanent flag sends a 301; redirect sends a 302. Important: rewrite appends the original query string automatically unless you add a trailing ? to the replacement.

location block — Scoped Configuration

location = /old-page {
    return 301 https://example.com/new-page;
}

location ^~ /old-section/ {
    return 301 https://example.com/new-section$request_uri;
}

A location block confines the redirect to a specific URI or prefix. Use = for exact match (fastest), ^~ for prefix match (skips regex locations), or ~/~* for regex match. Inside the block you typically use return.

Query String Handling

How query parameters are handled depends on the directive:

  • With return: Query strings are not appended automatically. To preserve them, append $is_args$args to the target URL. $is_args outputs ? only if a query string exists, avoiding a trailing ? on clean URLs.
  • With rewrite: Query strings are appended automatically. To strip them, add a trailing ? to the replacement URL (e.g., rewrite ^/old$ /new? permanent;).

Common Redirect Patterns

Force HTTPS

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

This catches all HTTP traffic on port 80 and redirects to the same host and URI on HTTPS. The $host variable preserves whether the user visited example.com or www.example.com.

Canonical Domain (www vs non-www)

server {
    listen 443 ssl;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

Pick one canonical form — www or non-www — and redirect the other to it. This prevents duplicate content in search indexes and consolidates link equity on one domain.

Trailing Slash Normalization

rewrite ^([^.]*[^/])$ $1/ permanent;

Adds a trailing slash to all URLs that don't have one and don't contain a file extension. Consistent trailing-slash behavior prevents duplicate content issues and avoids relative-path breakage in HTML.

Testing and Debugging Redirects

Before deploying any redirect configuration:

  • Validate syntax: Run nginx -t to check for configuration errors before reloading.
  • Test with curl: Use curl -I http://example.com/old-page to inspect the response headers. Look for the correct Location header and status code.
  • Check redirect chains: Ensure there are no redirect loops (A→B→A) or chains (A→B→C→D). Each hop adds latency and may cause search engines to drop the page. Aim for a single redirect from source to final destination.
  • Clear browser cache: Browsers cache 301 redirects indefinitely. Use incognito mode or curl when testing to avoid stale cached redirects.
  • Monitor 404s: After deploying redirects, check your access logs for 404s on the old URLs — they indicate rules that are not matching.

SEO Considerations for Redirects

Redirects directly affect how search engines treat your URLs:

  • 301 passes link equity. Google has confirmed that 301 redirects pass full PageRank to the target URL (as of 2016). This makes 301 the right choice for permanent moves.
  • Avoid redirect chains. Google follows up to 10 redirects, but each hop dilutes crawl budget. Consolidate chains into single hops where possible.
  • Update internal links. After setting up redirects, update your site's internal links to point directly to the new URLs. Redirects are for external links and bookmarks — your own site should link to the canonical URL.
  • Keep redirects for at least 1 year. Search engines may take months to recrawl and update their index. Removing redirects too early means losing the link equity from external backlinks.

FAQ

Common questions

What is the difference between a 301 and 302 redirect in Nginx?

A 301 redirect is permanent — browsers and search engines cache it, and link equity passes to the new URL. A 302 redirect is temporary — browsers re-check the original URL on every visit, and search engines keep indexing the old URL. Use 301 when the move is final (domain migration, URL restructure) and 302 when the redirect is short-lived (A/B test, maintenance page).

Should I use return, rewrite, or a location block for redirects?

The `return` directive is the simplest and most efficient — Nginx processes it without evaluating regular expressions. Use it when you know the exact source path. The `rewrite` directive is necessary when you need regex pattern matching (e.g. redirecting an entire directory with a wildcard). A `location` block wrapping a `return` is useful when the redirect applies only to a specific URI or prefix. For simple path-to-path redirects, `return` is the recommended choice.

How do I preserve query parameters during a redirect?

With the `return` directive, append `$is_args$args` to the target URL — this passes the query string only if one exists. With `rewrite`, Nginx appends query parameters automatically unless you add a trailing `?` to the replacement URL (which strips them). This tool handles both behaviors with the "Preserve query parameters" checkbox.

What is the difference between 307 and 308 redirects?

307 (Temporary Redirect) and 308 (Permanent Redirect) guarantee that the HTTP method is preserved — a POST stays a POST. Standard 301 and 302 redirects may (and in practice do) change POST requests to GET. Use 307/308 for API endpoints or form submissions where the method matters.

How do I redirect an entire domain to a new domain in Nginx?

Create a dedicated `server` block that listens for the old domain and returns a 301 redirect to the new domain with `$request_uri` appended to preserve the path. Use the "Domain migration" preset in this tool to generate the configuration. Place this server block before your main server block in the Nginx config.

Where do I put redirect rules in the Nginx config file?

Redirects go inside a `server` block in your Nginx configuration (typically `/etc/nginx/sites-available/your-site.conf` or `/etc/nginx/conf.d/your-site.conf`). Domain-level redirects (HTTP→HTTPS, www→non-www) get their own `server` block. Path-level redirects go inside the existing `server` block that handles the domain. Always run `nginx -t` to test configuration syntax before reloading.

How do I redirect HTTP to HTTPS in Nginx?

Create a separate server block listening on port 80 that returns a 301 redirect to the HTTPS version: `return 301 https://$host$request_uri;`. This tool generates the complete server block when you use the "HTTP → HTTPS" preset. Make sure your SSL certificate is configured in the port 443 server block before enabling this redirect.

Can I use regex in Nginx redirects?

Yes — the `rewrite` directive supports PCRE regular expressions. For example, `rewrite ^/blog/(.*)$ /articles/$1 permanent;` redirects all URLs under /blog/ to /articles/ while preserving the path. The `location` directive also supports regex with the `~` (case-sensitive) or `~*` (case-insensitive) modifiers. Enable the "Treat source as regex" option in this tool to use your pattern as-is without auto-escaping.

More in Developer Tools