Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 30 ยท Serving Content

Redirects and Rewrites

Learn redirects and rewrites in nginx and Apache: return vs rewrite, RewriteRule and RewriteCond, flags, canonical host, HTTP to HTTPS and redirect loops.

Sooner or later every site needs to change an address: a page moves, www should lead to the bare domain, http should lead to https, or /blog/42 should quietly be served by index.php?post=42. Web servers do all of this with two different mechanisms that beginners constantly mix up. A redirect tells the browser to go somewhere else, and the address bar changes. A rewrite changes the request inside the server, and the browser never knows.

In this lesson you will learn both mechanisms in nginx (return, rewrite) and Apache (Redirect, mod_rewrite), read the flags that control what happens after a match, build the three redirects every site needs, and understand how redirect loops arise. A small JavaScript engine lets you run both rule styles and compare them.

Redirect or rewrite?

Two different tools

Redirect The browser is told a new URL and asks again.
Rewrite The server maps the URL to something else, invisibly.

Redirects change the address bar. Rewrites do not.

1 / 2

Use a redirect whenever the public address should change: an old URL, a canonical host, a forced scheme. Use a rewrite when the URL stays but the file or program that serves it differs, as with clean URLs. Search engines treat a 301 as "update your index", so pick it only when you mean it; a wrongly cached 301 is hard to undo because browsers keep it. Test with 302 first, then switch to 301.

The real nginx and Apache configuration here is shown in read-only blocks, because the site cannot run a web server. The interactive examples are a JavaScript stand-in: a small engine that follows the same rules, so you can see what each rule does. It is not nginx or Apache, and real servers have more details than this model.

Nginx: return and rewrite

In nginx, return is the simple, fast tool. It stops processing and sends the answer:

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

$request_uri is the original path with the query string, so /shop?id=3 arrives intact on the other side. This one block is the whole "HTTP to HTTPS plus canonical host" job, and it is better than any if condition you could write.

rewrite takes a regular expression, a replacement and an optional flag:

NGINX
rewrite ^/old/(.*)$ /new/$1 permanent;
rewrite ^/docs/(\d+)$ /documents/$1.html last;

The regex is matched against the path only (no query string, which nginx appends to the replacement on its own). Captured groups become $1, $2 and so on. The flag decides what happens next:

Flag Effect
(none) Continue with the next directives in the same block
last Stop here, then search for a matching location again using the new URI
break Stop here and keep serving from the current location
redirect Send a 302 redirect to the replacement
permanent Send a 301 redirect to the replacement

A replacement that starts with http:// or https:// is always a redirect. The difference between last and break matters most inside a location block: last restarts the search (the new URI might land in another location), while break does not. More on the location search in Location Blocks and Matching Order.

Prefer return over rewrite whenever you do not need a regex capture, and never use if for host or scheme tests: use separate server blocks, as above (see Server Blocks and Choosing a Server). For a long list of old URLs, a map block is cleaner than fifty rewrite lines:

NGINX
map $uri $new_uri {
    /old-pricing   /pricing;
    /old-about     /company;
}

server {
    if ($new_uri) { return 301 $new_uri; }
}

Using if with return as shown is one of the few safe uses of if in nginx.

Apache: Redirect and mod_rewrite

Apache gives you two modules. The simple one is mod_alias:

APACHE
Redirect permanent /old-page /new-page
RedirectMatch 301 "^/blog/([0-9]+)$" "/posts/$1"

Redirect matches by prefix: /old-page also redirects /old-page/extra to /new-page/extra. RedirectMatch takes a regex, with captures as $1. For everything else there is mod_rewrite, which you must load (a2enmod rewrite on Debian):

APACHE
RewriteEngine On

# send plain HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# drop the www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

Here is how to read it. A RewriteRule has three parts: a pattern matched against the path, a substitution, and flags in brackets. One or more RewriteCond lines before it add extra tests; all of them must be true (or use [OR]). A RewriteCond belongs to the next rule only. In substitutions, $1 refers to the rule's pattern and %1 to the last matching condition. Common flags:

  • R=301: make it an external redirect (plain R means 302).
  • L: last, stop processing the rules.
  • NC: ignore case.
  • QSA: append the original query string to the substitution.
  • END: stop, and do not let any further rewriting round happen.
  • F: answer 403 Forbidden, G: answer 410 Gone.

Beware one difference between contexts. Inside a <VirtualHost> the pattern sees the full path starting with a slash (^/old/). Inside a <Directory> block or a .htaccess file it sees the path without the leading slash (^old/), and after a rewrite the engine starts over for the new URL, so L does not stop it from running the rules again. That second behavior is a classic cause of loops in .htaccess files, which END or a guarding condition prevents. See .htaccess, Directory Rules and AllowOverride for the context rules.

If you can, prefer the plain Redirect directives for simple moves: they are easier to read and less error-prone than mod_rewrite.

The same rules in a stand-in engine

The engine below implements both styles: nginx-like return and rewrite with flags, and Apache-like RewriteCond plus RewriteRule. It applies the rules to the same requests so you can compare results.

JS Stand-in: a rewrite engine with both rule styles

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the second request: the query string id=3 stays attached in the nginx result thanks to $request_uri. In Apache, %{REQUEST_URI} does not contain the query, but real Apache appends the original query string automatically when a substitution has no ? of its own (the QSA flag is for adding it to a substitution that does have one), and the stand-in copies that behavior, so both addresses agree. The fourth request shows an internal rewrite: /docs/42 is served as /documents/42.html with no redirect, and the visitor still sees /docs/42.

Loops, trailing slashes and other traps

A redirect loop happens when a rule's output matches its own input. The browser reports "too many redirects" (ERR_TOO_MANY_REDIRECTS). Common causes: forcing HTTPS in a server that also receives plain HTTP from a TLS-terminating proxy (so the app sees "http" forever), a rule like www to non-www combined with another rule that does the reverse, and a rewrite ... last whose result matches the same location. Nginx stops internal loops after 10 cycles with a 500 error and the message "rewrite or internal redirection cycle"; the test below shows the shape.

JS Stand-in: how a rewrite loop is cut off

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Trailing slashes deserve one rule of thumb: pick one form and redirect the other to it. Nginx and Apache both redirect a directory request without a slash (/docs to /docs/) when a directory with that name exists, so a rule that fights that redirect can loop. Keep rewrite rules narrow: match only the paths you mean, and always test with curl -I, which shows the status code and Location header without following redirects:

Terminal
curl -I http://example.com/old/page
# HTTP/1.1 301 Moved Permanently
# Location: https://example.com/new/page

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the visible difference between a redirect and an internal rewrite?

    A redirect sends a Location header and the browser requests the new URL. An internal rewrite changes only what the server serves; the address bar keeps the original URL.
  2. 2. In nginx, which flag stops rewriting and then searches the location blocks again with the new URI?

    last ends the current rewrite processing and restarts the location search. break stops rewriting but stays in the current location.
  3. 3. In Apache, a RewriteCond line applies to which rule?

    Conditions are attached to the next RewriteRule. Multiple conditions in a row are combined with AND unless marked [OR].
  4. 4. Why should you try a 302 before switching a new redirect to 301?

    Permanent redirects are cached by browsers and remembered by search engines. A wrong one can keep hurting visitors long after you fix the server.
  5. 5. Which nginx directive is the best choice for a plain 'send everything to the HTTPS version' job?

    A separate server block with return is clear, fast and avoids the pitfalls of if. It also keeps the query string via $request_uri.

Summary

  • A redirect changes the address in the browser; a rewrite maps the URL internally.
  • Nginx: return for simple redirects, rewrite with last, break, redirect or permanent when you need regex captures; avoid if for host and scheme tests.
  • Apache: Redirect/RedirectMatch for simple moves; RewriteCond plus RewriteRule with flags such as R=301, L, NC, QSA and END for everything else.
  • The three redirects every site needs are canonical host, HTTP to HTTPS and moved pages.
  • Redirect loops come from rules whose output matches their own pattern; keep patterns narrow and test with curl -I.
  • Start with 302, switch to 301 when you are sure.

Next: Static Files, Caching and MIME Types.