How to Set Up Redirects in Nginx Without Breaking Existing Rules
nginxserver-configredirect-rulesdeveloper-guidetechnical-seo

How to Set Up Redirects in Nginx Without Breaking Existing Rules

PPortal Redirect Editorial
2026-06-10
10 min read

A practical guide to setting up Nginx redirects safely, choosing the right rules, and avoiding chains, loops, and broken legacy URLs.

If you manage a live site on Nginx, redirects are one of the easiest places to create accidental downtime, redirect chains, or SEO loss. This guide explains how to add an Nginx redirect safely, choose the right directive, preserve existing behavior, and test changes before they affect users or crawlers. The goal is simple: make redirect rules predictable, maintainable, and easy to revisit as your site structure changes.

Overview

A redirect in Nginx is rarely just a single line of configuration. It sits inside a wider routing system that may include multiple server blocks, SSL rules, reverse proxy behavior, CMS rewrites, CDN settings, and application-level routing. That is why many broken redirects are not caused by the redirect itself, but by where it was placed, how broadly it matches, or what other rules already exist.

For most website owners and developers, the safest approach is to treat redirects as part of a hierarchy:

  • Canonical host and protocol redirects, such as HTTP to HTTPS or www to non-www
  • Domain-level redirects, such as moving one domain to another
  • Path-based redirects, such as changing /old-page to /new-page
  • Pattern-based redirects, such as migrating an entire section
  • Application or CMS routing, which should only take over after server-level rules are clear

That order matters. If your canonicalization rules are inconsistent, path redirects often appear to work in one case and fail in another. A URL may redirect correctly on HTTPS but not on HTTP, or on the apex domain but not on the www hostname. Before you add anything new, identify the canonical version of the site and make sure all variants eventually resolve to it in a single step where possible.

It also helps to decide what kind of redirect you actually need. A permanent move usually calls for a 301 redirect. A temporary move may call for a 302 or 307 depending on the use case. If you need a refresher on status code choice, see 301 vs 302 vs 307 Redirects: When to Use Each for SEO and User Experience.

In Nginx, the key lesson is this: do not start by pasting redirect snippets into random locations. Start by mapping the request flow, then insert the smallest rule that solves the problem without colliding with existing behavior.

Core framework

Use this framework whenever you set up a new Nginx redirect or revise old redirect rules. It is designed to reduce surprises and keep configuration manageable over time.

1. Inventory the current routing logic

Before editing config files, answer a few basic questions:

  • Which hostnames point to this server?
  • Is Nginx serving content directly, proxying to an app, or both?
  • Are redirects already happening at the CDN, load balancer, or application layer?
  • Are there separate configs for HTTP and HTTPS?
  • Do any regex locations or rewrites already affect the target paths?

This step prevents a common mistake: adding a new redirect to Nginx when the request is already being rewritten elsewhere. If two layers try to enforce slightly different logic, you often end up with chains or loops.

2. Prefer the simplest directive that fits

For many cases, return is cleaner and safer than rewrite. It is easier to read, more explicit, and usually better for straightforward redirects.

Typical pattern:

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

Use return when you know the destination URL. Reserve rewrite for cases where you need pattern matching and substitutions.

Simple path redirect:

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

Section migration with pattern matching:

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

Even when rewrite works, do not default to it if a direct return is enough.

3. Keep broad redirects above narrow fixes in your planning, but precise in your config

You usually want global canonical redirects to happen before content-specific routing. For example, force HTTPS first, then resolve host preference, then apply page-level redirects. The exact mechanics depend on your server blocks, but the intent should be consistent: every possible version of a URL should converge on one final destination without unnecessary hops.

If you are standardizing hostnames, this guide pairs well with WWW vs Non-WWW Redirect Strategy: Best Practices for Canonical Consistency and HTTP to HTTPS Redirect Checklist for Websites, Subdomains, and Legacy URLs.

4. Match as narrowly as possible

Overly broad redirect rules are one of the fastest ways to break existing URLs. If one page moved, redirect one page. If one folder moved, redirect that folder. Do not use a regex that catches more than you intend unless you have tested all affected URL patterns.

Safer exact match:

location = /pricing-old {
    return 301 /pricing;
}

Broader pattern, only when justified:

rewrite ^/store/(.*)$ /shop/$1 permanent;

The second rule is efficient during a section migration, but risky if /store/ still contains exceptions or mixed content paths.

5. Preserve query strings when they matter

Campaign links, filtered category pages, and app flows often depend on query parameters. In some redirect patterns, Nginx preserves them; in others, your configuration may unintentionally drop them. If attribution and analytics matter, test with real URLs that include UTM parameters or other tracking values.

For marketing-heavy sites, that detail is not minor. Losing query strings can damage campaign reporting and attribution. If redirected links are part of your measurement setup, also review Real-Time Analytics for Website Owners: What to Log, What to Ignore, and What to Automate and Why Fast Sites Need Better Data Pipelines: The Link Between Performance, Tracking, and Revenue.

6. Separate redirect intent from routing complexity

Many teams inherit Nginx configs where redirects, proxy rules, cache settings, and application rewrites are mixed together. That makes future changes dangerous. A more maintainable pattern is to group redirect rules by purpose:

  • Protocol and hostname canonicalization
  • Legacy URL redirects from old site structures
  • Campaign or short-link behavior, if handled at Nginx
  • Temporary redirects used for limited operational cases

Even if your final config lives in a single file, organizing it this way makes audits much easier.

7. Validate config before reload

Never reload Nginx on a production server without syntax testing first. A typical workflow is:

  1. Edit the config
  2. Run a config test such as nginx -t
  3. Review the affected server blocks
  4. Reload only after validation passes

Syntax validation does not guarantee logic is correct, but it catches structural mistakes early.

8. Test redirects as user journeys, not isolated lines

After deployment, test complete request paths:

  • HTTP to HTTPS
  • www to non-www or the reverse
  • Old URLs to new URLs
  • URLs with query parameters
  • Trailing slash and non-trailing slash variants
  • Uppercase, lowercase, and encoded URLs if your site receives them

A redirect that succeeds in one browser test may still produce a chain across multiple variants. This is where a redirect checker or redirect audit process becomes useful.

Practical examples

The examples below are reference patterns. Adjust hostnames, paths, and placement to fit your actual Nginx layout.

HTTP to HTTPS redirect

This is one of the most common and useful canonical redirects.

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

This pattern redirects all HTTP traffic to the preferred HTTPS host while preserving the request URI.

WWW to non-WWW redirect

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

Use a separate server block for the non-canonical host when possible. It is usually clearer than trying to fold everything into one complex conditional structure.

Single page redirect

location = /old-contact {
    return 301 /contact;
}

This exact-match approach avoids catching nearby URLs accidentally.

Entire directory migration

rewrite ^/resources/(.*)$ /guides/$1 permanent;

This can work well when an entire section has moved and the path structure remains parallel. Before using it, verify there are no exceptions inside the old directory.

Redirect one domain to another

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

For a domain redirect during rebranding or consolidation, pair this with a URL mapping review so valuable legacy pages do not all collapse to the homepage. One-to-one mappings are usually better than blanket homepage redirects when old content has strong backlinks or search visibility.

Temporary maintenance redirect

location = /campaign-landing {
    return 302 /temporary-version;
}

Use temporary status codes deliberately, and document when they should be removed. Temporary redirects that linger for months often become unplanned permanent behavior.

Pattern with captured groups

rewrite ^/category/(.*)/(.*)$ /topics/$1/$2 permanent;

This is useful in structured migrations, but it deserves careful testing. Regex-based nginx redirect rules can save time, yet they are also the easiest way to create edge-case failures.

Configuration note for CMS and app stacks

If Nginx fronts WordPress, a headless CMS, or a custom app, decide whether the redirect belongs at the server layer or inside the application. Server-level redirects are often better for canonical host, protocol, and legacy path changes that apply to all traffic. Application-level redirects may be easier for content editors to manage if they change frequently. The wrong split leads to duplicated logic and hard-to-debug behavior.

If you work across multiple server types, compare your approach with How to Set Up 301 Redirects in Apache .htaccess so your redirect governance stays consistent across environments.

Common mistakes

Most Nginx redirect issues come from a short list of repeatable errors. If you avoid these, your config will be much more stable.

Placing redirects in the wrong context

A rule may be syntactically valid but ineffective because it sits in the wrong server block or conflicts with a more specific location match. Always confirm which block handles the incoming request.

Creating redirect chains

A request should ideally reach its final destination in one redirect. Chains often happen when you stack protocol, host, and path changes without checking the combined result. For example:

  • http://www.example.com/old-page → HTTPS
  • HTTPS www → non-www
  • old-page → new-page

That sequence may work, but it is still inefficient. A better setup consolidates those rules so the user lands on the final canonical URL as directly as possible. For cleanup strategies, see How to Fix Redirect Chains and Loops Before They Hurt SEO and Speed.

Causing redirect loops

Loops usually come from contradictory rules, such as forcing HTTPS in one place while another layer routes traffic back to HTTP, or redirecting www to non-www while another service enforces the opposite. If you use Cloudflare, a load balancer, or a platform proxy, check those layers too.

Using regex when exact matches would do

Regex is useful, but every extra pattern increases maintenance risk. If only five legacy URLs matter, five explicit rules may be safer than one clever catch-all.

Forgetting query strings and campaign tracking

If a redirected landing page receives paid traffic, email clicks, or QR scans, test UTM parameters explicitly. Broken attribution can be as costly as a broken page, especially during active campaigns.

Redirecting everything to the homepage

This is common in rushed migrations. It may feel clean operationally, but it often creates a poor user experience and wastes link equity from pages that had clear modern equivalents. During site migration SEO work, map old URLs to the most relevant new destinations whenever possible.

Leaving temporary rules undocumented

Short-term redirects for launches, A/B testing, maintenance, or campaign swaps should have an owner and a review date. Otherwise they linger, conflict with later changes, and make future audits much harder.

Testing only in the browser

Browser tests are useful, but cached behavior can hide problems. Use repeatable checks that verify status codes, locations, and final landing URLs across multiple variants. A redirect checker or command-line request tool helps confirm what is really happening.

When to revisit

Your redirect setup should not be a one-time task. Revisit it whenever the site structure, delivery stack, or measurement requirements change. Redirects age quietly, and rules that were safe last year may become technical debt after a redesign or infrastructure change.

Plan a review when any of these events happen:

  • You redesign navigation or change URL patterns
  • You move from HTTP to HTTPS or change certificate handling
  • You switch between www and non-www canonical versions
  • You launch a new CDN, proxy, or edge redirect layer
  • You migrate content into or out of a CMS
  • You retire product pages, resources, or campaign landing pages
  • You merge domains or rebrand
  • You notice crawl waste, redirect chains, or unexplained drops in landing-page performance

A practical review process looks like this:

  1. Export important URLs from analytics, sitemaps, and backlink sources
  2. Check final destinations for top pages, legacy URLs, and campaign links
  3. Remove dead temporary rules that no longer serve a purpose
  4. Consolidate duplicate logic across Nginx, CDN, and application layers
  5. Document intent for each major redirect group
  6. Retest after every infrastructure change

If your site depends on redirects for migrations, analytics, or canonicalization, build a small redirect audit into regular technical SEO maintenance. Even a lightweight review can catch loops, outdated mappings, and broken attribution before they become bigger problems.

The long-term goal is not to accumulate more redirect rules. It is to keep only the rules that still have a clear purpose, behave consistently, and lead users and crawlers to the right final URL in as few steps as possible.

Related Topics

#nginx#server-config#redirect-rules#developer-guide#technical-seo
P

Portal Redirect Editorial

Senior SEO Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.