← Back to blog

Nginx Rewrite Examples: 301s, HTTPS and www Redirects

October 30, 2026
Nginx Rewrite Examples: 301s, HTTPS and www Redirects

Most Nginx redirects need one line, not a regex. Use return 301 when the destination is fixed or can be built from variables like $scheme, $host and $request_uri. Use rewrite only when you have to match a pattern and reuse pieces of the old URL in the new one. Below are working examples for the jobs people actually search for: a 301 for an old path, forcing HTTPS, www to non-www (and back), mapping old URLs with captures, and avoiding loops.

Pingfloat
Check Your Site’s Availability
After updating Nginx redirects, use Pingfloat’s uptime monitoring and SSL checks to keep an eye on website availability and security.
Explore Pingfloat tools

TL;DR

  • Prefer return 301 https://example.com$request_uri; for host and protocol redirects. It is simpler and skips regex work.
  • Put each redirect in its own server block chosen by server_name, not in an if inside the main site.
  • Use rewrite ... permanent; only when a regex capture is needed, and add break or last deliberately to avoid loops.
  • Always run sudo nginx -t before sudo systemctl reload nginx, then confirm with curl -I.

Table of Contents

Return or rewrite: which one to use

Both directives live in the rewrite module, and both can send a redirect. The difference is how much work they do. According to the NGINX community blog, return suits a fixed destination or status response and stops processing immediately, while rewrite is for cases where a regex must match, capture parts of the URL, or change or add path elements. A guide on 301, 302 and 307 redirects also recommends return for simple redirects because it avoids unnecessary regex processing.

The syntax of return is return code [text] or return code URL. The official module reference lists redirect-capable codes including 301, 302, 303, 307 and 308.

A quick rule of thumb:

You want to...Use
Send every request on a host to another hostreturn 301
Force HTTPSreturn 301 in a port-80 server block
Move /old-blog/anything to /blog/anythingrewrite with a capture
Change the URI internally without a redirectrewrite without permanent or redirect
Return a status page or messagereturn 403; or return 410;

If you are unsure whether a move should be permanent or temporary, our guide to 301 vs 302 redirects covers the SEO consequences. Short version: 301 for a move that will not be undone, 302 for one that might be.

A basic Nginx 301 redirect

The most common case is a domain move where paths stay the same. The NGINX blog gives this pattern: return 301 $scheme://www.new-name.com$request_uri;, and notes that $request_uri carries the path and arguments (source).

server {
    listen 80;
    listen 443 ssl;
    server_name old-name.com www.old-name.com;

    # ssl_certificate lines for the old name go here

    return 301 $scheme://www.new-name.com$request_uri;
}

Three details matter here:

  1. $request_uri is the original URI including the query string, so /pricing?plan=pro arrives intact at the new host.
  2. $scheme keeps the protocol the visitor used. If you want to force HTTPS at the same time, write https:// literally.
  3. The 443 listener still needs a valid certificate for the old name, otherwise browsers show a TLS error before they ever see your redirect.

A single page moving is just as short:

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

The = makes it an exact match, so /old-page-archive is not caught by accident.

Redirect HTTP to HTTPS (force HTTPS)

The standard way to redirect all traffic to HTTPS is a dedicated server block on port 80. As Vultr's documentation describes it, you define a server listening on port 80 and use return 301 https://example.com$request_uri;.

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com/fullchain.pem;
    ssl_certificate_key /etc/ssl/example.com/privkey.pem;

    # site config
}

If you host many domains on one server and do not want to repeat the block, a catch-all variant uses the host the visitor asked for:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    return 301 https://$host$request_uri;
}

People often search for "nginx rewrite http to https", and older answers show rewrite ^ https://$host$request_uri permanent;. It works, but return does the same thing without running a regex, so there is no reason to prefer it.

After the redirect works, check that your certificate is valid and not close to expiry. Our SSL Checker shows the certificate chain, issuer and expiry date for any hostname, which is handy right after you switch traffic to port 443.

Redirect www to non-www (or the reverse)

Pick one canonical hostname and send the other to it. For www to non-www, give the www name its own server block. A tested guide points out that $request_uri preserves the path and all query parameters.

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

For the reverse, non-www to www:

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

Why a separate block instead of an if ($host = ...) inside the main server? NGINX's own conversion guide recommends separate server blocks for host canonicalization rather than an if plus rewrite: one block redirects example.org to www.example.org, another serves www.example.org. It is clearer, it is cheaper per request, and it avoids the surprises if is known for inside location contexts.

One trap: do not write return 301 http://example.com$uri;. $uri is the normalized path without arguments, so the query string is dropped. A guide to canonical redirects shows the same difference: $request_uri keeps the query string, $uri alone loses it.

HTTPS and canonical host together

Forcing HTTPS and picking www or non-www at the same time is where most double-redirect chains appear. If port 80 sends everything to https://example.com and the HTTPS block for example.com then sends to www, a visitor on http://www.example.com can bounce more than once. The cleanest layout uses three server blocks, as the ZeroExp guide describes: port 80 redirects both hostnames straight to the canonical HTTPS host, HTTPS on the bare host redirects to www, and HTTPS on www serves the site.

Four URL entry points routed to canonical HTTPS host

# 1. Everything on port 80 goes straight to the canonical HTTPS host
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://www.example.com$request_uri;
}

# 2. HTTPS on the bare host redirects to www
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com/fullchain.pem;
    ssl_certificate_key /etc/ssl/example.com/privkey.pem;

    return 301 https://www.example.com$request_uri;
}

# 3. The real site
server {
    listen 443 ssl;
    server_name www.example.com;

    ssl_certificate     /etc/ssl/example.com/fullchain.pem;
    ssl_certificate_key /etc/ssl/example.com/privkey.pem;

    # site config
}

The same guide warns that the HTTPS block for the non-canonical hostname still needs a certificate covering that hostname. TLS completes before NGINX can issue the redirect, so without a matching certificate the visitor sees a browser warning instead of your 301. A certificate listing both example.com and www.example.com solves it.

The result: any of the four entry points reaches the final URL in at most one redirect, and only http://example.com and https://example.com need a single hop each.

Rewrite examples for old URLs

When the new URL depends on part of the old one, rewrite earns its place. The syntax is rewrite regex replacement [flag];.

Move a directory and keep the rest of the path

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

The parentheses capture everything after /old-blog/, and $1 drops it into the new path. permanent sends a 301. Testing a pattern like this against sample paths before it goes live saves a lot of pain, and our Regex Tester lets you check matches and capture groups in the browser. Keep in mind it runs JavaScript regex, while Nginx uses PCRE, so stick to common syntax.

Turn a query-string URL into a clean one

A frequent question: change /show_page.php?name=terms to /pages/terms.html. Query strings are not part of the rewrite match, so test the argument with a condition:

location = /show_page.php {
    if ($arg_name ~ ^[a-z0-9-]+$) {
        return 301 /pages/$arg_name.html;
    }
}

Here return inside if is one of the safe uses of if, because nothing else is processed after it.

Watch what happens to the query string

The official reference states that if a replacement includes new request arguments, the old arguments are appended after them. To drop the old ones, end the replacement with a question mark:

rewrite ^/search/(.*)$ /find?q=$1? permanent;

Without the trailing ?, the visitor's original query string would be tacked onto the new one.

Retire a whole section with a single 410

Not every old URL needs a destination. If a section is gone for good:

location /discontinued/ {
    return 410;
}

Rewrite before a reverse proxy

A common request: expose /app/ while the backend serves from the root. This is an internal rewrite, with no redirect for the client:

location /app/ {
    rewrite ^/app/(.*)$ /$1 break;
    proxy_pass http://127.0.0.1:3000;
}

The break flag stops rewrite processing so the rewritten URI goes straight to proxy_pass. Note that with a URI part in proxy_pass, Nginx replaces the matched location part itself, which is why this pattern is easy to double up. If you rewrite, keep proxy_pass without a path.

Flags and redirect loops

The flag at the end of rewrite changes what happens next. The official documentation defines them like this:

FlagEffect
lastStops the current rewrite directives and starts a new search for a matching location
breakStops rewrite processing in the current context
redirectReturns a 302 temporary redirect
permanentReturns a 301 permanent redirect

The flags are the source of most loops. According to the module reference, a rewrite loop can hit the built-in limit of 10 cycles and produce a 500 error, and in the documentation's own example break is required when the rewrites sit inside the /download/ location. Using last inside a location that the rewritten URI matches again sends the request around the cycle.

How to stay out of trouble:

  • Use break when a rewrite inside a location should end there.
  • Make redirect rules mutually exclusive: each hostname and scheme combination should match exactly one block.
  • Never redirect a URL to something that the same rule matches. rewrite ^/blog/(.*)$ /blog/$1 is the classic accident.
  • Avoid host checks in if blocks. Use separate server blocks.

If a loop does slip through, the visitor sees an error rather than a page. Our reference on the 500 Internal Server Error explains the usual causes, and the Nginx error log will name the rewrite cycle directly. If you would rather skip the permanent or temporary decision for a method-preserving move, the 308 Permanent Redirect page explains how it differs from 301 for POST requests.

Our perspective

We build tools for people who run websites, and redirect problems show up in our work constantly, usually not as a syntax error but as a silent one. The config reloads cleanly, the homepage works, and three weeks later someone notices that http://www takes two hops, or that a campaign URL lost its query string.

Our perspective — overview diagram

Our advice is boring on purpose. Write redirects as return statements in dedicated server blocks, one block per entry point, and resist cleverness. Regex rewrites are for the moments you truly need a capture. Then verify from the outside, with real requests, after every change. A config test only proves Nginx can read the file, not that visitors land where you meant.

We also think redirects deserve monitoring like anything else. A rule that works today can be broken by a later edit to an unrelated block, and the first sign is often a drop in traffic. Watching the final URL and its status code is cheap insurance.

— Andreas

Test and reload safely

Every change follows the same three steps.

  1. Back up the current configuration file before editing.
  2. Check syntax with sudo nginx -t. As a guide to safe reloads puts it, run the test first, and only if it passes apply the change with sudo systemctl reload nginx, which reloads without interrupting active connections.
  3. Request the URL with curl and read the response headers.
curl -I http://example.com/pricing?plan=pro

The -I flag shows the status line and Location header, so you can confirm the status and destination, a method also noted in Rackspace's redirect docs. Use curl -IL to follow the whole chain and count the hops. You want one hop at most for any entry point.

Check these cases every time:

  • http://example.com/ and http://www.example.com/
  • https://example.com/ and https://www.example.com/
  • A deep URL with a query string
  • One old URL that should hit a rewrite rule

For more on the checking side, see our 3 quick checks to test redirects. If you also run Apache somewhere, the equivalent rules are in our Apache 301 redirect guide, and our broader write-up on Nginx redirect rules goes through more variations.

Generate the rules instead of typing them

If you would rather not hand-write every block, the free Redirect Rule Generator produces Nginx and Apache redirect rules from the source and target you enter. Paste the result into your config, run nginx -t, and you are done. Once the redirects are live, our Website Uptime Monitor can keep an eye on the final URL, so a broken rule does not go unnoticed. The core tools need no installation and no account.

Pingfloat

FAQ

Should I use rewrite or return for a 301 redirect in Nginx?

Use return 301 whenever the destination is fixed or built from variables such as $request_uri. It stops processing at once and does no regex work. Choose rewrite ... permanent; only when you must capture part of the old URL and reuse it in the new one.

How do I redirect all traffic to HTTPS in Nginx?

Create a server block that listens on port 80 and returns 301 https://example.com$request_uri;. That sends every HTTP request to the same path and query string on HTTPS. Make sure the HTTPS server block has a valid certificate before you switch.

Why did my redirect drop the query string?

You probably used $uri in the target, which holds the normalized path without arguments. Use $request_uri instead. With rewrite, remember that arguments in the replacement cause the old ones to be appended unless you end it with a ?.

What causes a rewrite or redirect loop?

Usually a rule whose output matches its own pattern, or last used inside a location that the new URI hits again. Nginx stops after 10 cycles and returns a 500 error. Use break inside the location, or split host and scheme redirects into separate server blocks.

Do I need to restart Nginx after changing a redirect?

No. Run sudo nginx -t to validate the file, then sudo systemctl reload nginx. A reload applies the new configuration without dropping active connections.

Sources