Sub topic 14
Writing redirects in nginx and Apache
This chapter assumes you can read a basic nginx or Apache configuration file. It also assumes you know the difference between a 301 and a 302 response, and that you can run curl from a terminal. The goal is to write redirects that go straight to the final URL in one hop, and to test each rule before you rely on it.
What a redirect rule must do
A redirect rule tells the server to answer a request with a 3xx status code and a Location header. The client then requests the new URL. A good rule has three properties:
- It matches only the URLs you mean to move.
- It points to the final destination, not to another URL that redirects again.
- It uses a status code that matches your intent.
Use 301 or 308 when the move is permanent. Use 302 or 307 when it is temporary. Chapter 4 covered the differences. In server configuration, 301 and 302 are the most common choices, and 308 and 307 are the choices when the request method must be preserved.
Redirects in nginx
nginx handles redirects in server and location blocks. The simplest tool is the return directive. It stops processing and sends the response immediately.
# Redirect an old URL straight to its final destination (one hop)
location = /old-page {
return 301 /new-page;
}
# Serve a custom page but keep the 404 status
error_page 404 /404.html;
location = /404.html {
internal;
}The first block uses location =, which is an exact match. It applies only to /old-page, not to /old-page/ or /old-page-2. Exact matches are the safest way to redirect a single URL, because they cannot catch other paths by accident.
When the target is a relative path such as /new-page, nginx builds an absolute Location header from the scheme and host of the request. If you want to control the host, write the full URL: return 301 https://example.com/new-page;.
Redirecting a whole section
To move a directory and keep the rest of each path, use a location prefix and a regular expression capture.
location ^~ /blog/2019/ {
rewrite ^/blog/2019/(.*)$ /archive/2019/$1 permanent;
}The ^~ modifier makes this prefix match win over regular expression locations. The permanent flag on rewrite sends a 301. Without a flag, rewrite would continue processing internally and the browser would never see a redirect.
Redirecting by host: the www and HTTPS cases
Many redirect chains come from stacking the HTTP to HTTPS rule on top of the non-www to www rule. A request for http://example.com/page can then take two hops. Avoid this by sending every variant to the final canonical URL in one rule.
server {
listen 80;
listen 443 ssl;
server_name example.com;
# ssl_certificate and ssl_certificate_key go here
return 301 https://www.example.com$request_uri;
}
server {
listen 80;
server_name www.example.com;
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl;
server_name www.example.com;
# ssl_certificate and ssl_certificate_key go here
# site configuration
}The variable $request_uri holds the original path and query string, so the rule keeps them intact. Every variant (http://example.com, https://example.com, http://www.example.com) ends at https://www.example.com after one redirect.
Many redirects with a map
For more than a handful of redirects, a map block keeps the rules in one table. It lives in the http context.
map $request_uri $redirect_target {
default "";
/old-page /new-page;
/products/widget-1 /shop/widget;
~^/news/(\d+)$ /articles/$1;
}
server {
listen 80;
server_name example.com;
if ($redirect_target) {
return 301 $redirect_target;
}
}An empty default means "no redirect". This is one of the few safe uses of if in nginx, because the body contains only return. Lookups in a map are fast even with thousands of entries, which makes this form suitable for migration redirect maps.
Redirects in Apache
Apache can use either the main server configuration or .htaccess files. The main configuration is faster and easier to reason about. Use .htaccess only when you cannot edit the main file, such as on shared hosting.
# Requires mod_alias
Redirect 301 /old-page https://example.com/new-page
ErrorDocument 404 /404.htmlRedirect from mod_alias matches by prefix. A rule for /old-page also matches /old-page/anything and appends the rest of the path to the target. That is useful for moving a directory. It is a trap when you only wanted one page to move. For an exact match, use RedirectMatch with anchors:
RedirectMatch 301 ^/old-page$ https://example.com/new-pagePattern-based redirects with mod_rewrite
When you need conditions, such as the host name or a query string, use mod_rewrite.
RewriteEngine On
# Send every non-canonical host or HTTP request to the final URL in one hop
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]The [OR] flag joins the two conditions. The rule fires if either is true. R=301 sends a permanent redirect and L stops processing further rules. Without R=301, Apache defaults to 302, which is a common source of redirects that stay temporary for years by mistake.
The 404 page keeps its status
Both examples above define a custom error page. The status stays 404 because the server serves the file as the body of an error response. Two details matter:
- In Apache,
ErrorDocument 404 /404.htmlmust use a local path. If you write a full URL such asErrorDocument 404 https://example.com/404.html, Apache sends a redirect to that URL. The final page then returns 200, which creates a soft 404. - In nginx,
error_page 404 /404.html;keeps the 404 status. Writingerror_page 404 =200 /404.html;would replace it with 200, which is the same mistake.
Comparing the two servers
| Task | nginx | Apache |
|---|---|---|
| Redirect one exact URL | `location = /a { return 301 /b; }` | `RedirectMatch 301 ^/a$ /b` |
| Redirect a directory | `rewrite ^/dir/(.*)$ /new/$1 permanent;` | `Redirect 301 /dir /new` |
| Large redirect table | `map` block | `RewriteMap` (needs main config) |
| Keep the query string | Automatic with `return` and `$request_uri` | Automatic with `Redirect`; use `QSA` or `%{QUERY_STRING}` in rewrites |
| Default redirect status | `return` requires you to name it; `rewrite` without a flag is internal | `Redirect` and `R` default to 302 |
Common errors
- Redirect loops. A rule such as
rewrite ^/(.*)$ /new/$1 permanent;also matches/new/page, so it runs again and again. Anchor the match to the old prefix, or add a condition. - Missing trailing-slash handling.
/old-pageand/old-page/are different URLs. Decide which is canonical and write exact rules for it. - Rule order in Apache.
mod_aliasandmod_rewriterun in different phases, so mixing them in the same scope gives surprising results. Pick one for a given set of URLs. - Forgetting to reload. nginx needs
nginx -tto check the syntax andnginx -s reloadto apply it. Apache needsapachectl configtestand a graceful restart. - Redirecting to a redirecting URL. Update the target when the destination itself moves, so the chain stays at one hop.
Testing every rule
After each change, trace the URL and confirm the result.
curl -sIL https://example.com/old-page | grep -iE '^(HTTP|location)'You should see exactly one 301 line followed by one Location line, then a 200 for the destination. Two redirect lines mean a chain. Then check the summary:
curl -sL -o /dev/null -w '%{num_redirects} redirects, final status %{http_code}, final URL %{url_effective}\n' https://example.com/old-pageThe expected output is 1 redirects, final status 200, final URL https://example.com/new-page. Also test the host and protocol variants, a URL with a query string, and a path that should not redirect, to make sure the rule does not match too much.
Exercise
A site has the rule Redirect 301 /shop https://example.com/store in its Apache configuration. A user requests /shop-sale. What happens, and how would you limit the rule to the exact path /shop?
Show answer
Redirect from mod_alias matches by path prefix only up to a path-segment boundary, so /shop-sale is not matched, but /shop/shoes is and goes to https://example.com/store/shoes. If you only want /shop to move and not its subpaths, use RedirectMatch 301 ^/shop$ https://example.com/store.
Exercise
You configure nginx with error_page 404 =200 /404.html;. Why does this hurt search visibility, and what is the fix?
Show answer
The =200 replaces the 404 status with 200, so crawlers see a successful page that says "not found". That is a soft 404. Change the directive to error_page 404 /404.html; so the body is your custom page and the status stays 404.