Sub topic 11
Redirecting www to the canonical host name
This chapter assumes you can write a basic server block, you know how listen and server_name select a block, and you can validate and reload Nginx with nginx -t and systemctl reload nginx. It covers one task: sending every request for an alternate host name to a single canonical name.
Why pick one canonical name
A site is often reachable under several names. example.com and www.example.com usually point at the same server. If both answer with the same content, you get three problems:
- Search engines may treat the two names as duplicate sites.
- Cookies set for one name are not sent to the other, so a user can appear logged out after following a link that uses the other name.
- Your logs and analytics split traffic across two hosts.
The fix is to choose one canonical name, for example example.com, and answer every request for the other name with a redirect. A redirect is an HTTP response with a 3xx status code and a Location header. The client then repeats the request at the new address.
The dedicated redirect block
The cleanest approach is a separate server block whose only job is to redirect. It matches the alternate name through server_name and returns a redirect.
server {
listen 80;
listen [::]:80;
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}The pieces work as follows:
server_name www.example.com;makes this block win the selection for requests whoseHostheader iswww.example.com.return 301 ...;stops processing at once and sends the response. No document root is needed because no file is served.$schemeishttporhttps, depending on how the request arrived. The redirect keeps the original scheme.$request_uriis the full original request URI, including the path and the query string. A request for/docs/page?id=7is redirected tohttp://example.com/docs/page?id=7.
The canonical block then lists only the canonical name:
server {
listen 80;
listen [::]:80;
server_name example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}Compare this with the first example in the tutorial, where one block listed both example.com www.example.com. If you move to the pattern here, remove www.example.com from the canonical block's server_name. Otherwise two blocks claim the same name on the same port, and Nginx warns about a conflicting server name and ignores the second one.
Choosing the status code
The status code tells clients and search engines how long to remember the redirect.
| Code | Meaning | Method on repeat | Typical use |
|---|---|---|---|
| 301 | Moved permanently | Clients may change POST to GET | Canonical host redirects |
| 302 | Found (temporary) | Clients may change POST to GET | Short-lived moves |
| 307 | Temporary redirect | Method is preserved | Temporary move of forms or APIs |
| 308 | Permanent redirect | Method is preserved | Permanent move where POST must survive |
For a www redirect, 301 is the usual choice. Browsers cache a 301 aggressively, sometimes with no expiry. If you test with 301 and make a mistake, your browser may keep following the wrong redirect even after you fix the configuration. While experimenting, use 302, or test with curl, which does not cache. Switch to 301 when the behavior is right.
Redirecting the other way
Some sites prefer www.example.com as canonical, for instance when the bare domain cannot be a CNAME record in DNS. The pattern is the same with the names swapped.
server {
listen 80;
listen [::]:80;
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}Pick one direction and use it everywhere: in redirects, in your TLS certificates, in application settings, and in links.
Redirecting several alternate names
One redirect block can list several names. It is useful when you own variants of a domain.
server {
listen 80;
listen [::]:80;
server_name www.example.com example.net www.example.net;
return 301 $scheme://example.com$request_uri;
}A wildcard such as *.example.com would also catch www, but it catches every other subdomain too, including ones you serve from their own blocks only if those have a more specific match. Nginx prefers an exact name over a wildcard, so a block with server_name app.example.com still wins over *.example.com. Even so, an explicit list is easier to audit.
The HTTPS part
Redirects with HTTPS need extra care, because the client must complete a TLS handshake before it can even send the request. The redirect block for www.example.com on port 443 therefore needs a certificate that is valid for the www name. If it has none, or has one for a different name, the browser shows a certificate warning and never sees the redirect.
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
return 301 https://example.com$request_uri;
}This works when one certificate covers both example.com and www.example.com, which is the normal result when you request both names from Let's Encrypt. Here the scheme is written as https rather than $scheme, since this block only serves HTTPS.
A complete setup usually has four blocks:
- Port 80,
www.example.com: redirect tohttps://example.com. - Port 80,
example.com: redirect tohttps://example.com. - Port 443,
www.example.com: redirect tohttps://example.com. - Port 443,
example.com: serve the site.
Redirecting straight to the final HTTPS canonical URL in block 1 avoids a chain of two redirects (http://www to http:// and then to https://). Each extra hop costs the visitor a round trip.
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}Blocks 1 and 2 are merged here because they share the same action.
Redirects inside a block with `if`
You may see this pattern in older guides:
server {
server_name example.com www.example.com;
if ($host = www.example.com) {
return 301 $scheme://example.com$request_uri;
}
}For a bare return inside if, this works and is safe. But the Nginx documentation warns that if inside a location behaves unexpectedly in many other cases. A dedicated block is selected before any request processing, costs nothing extra, and makes the intent obvious. Prefer it.
Testing the redirect
Use curl -I to fetch only the headers and avoid following the redirect, so you can see it. Combine it with --resolve to test before DNS changes, as covered earlier in this tutorial.
sudo nginx -t && sudo systemctl reload nginx
curl -I --resolve www.example.com:80:127.0.0.1 http://www.example.com/docs?id=7A correct setup returns output like this:
HTTP/1.1 301 Moved Permanently
Server: nginx
Location: http://example.com/docs?id=7Then confirm the canonical name answers directly without redirecting:
curl -I --resolve example.com:80:127.0.0.1 http://example.com/docsTo follow the whole chain and print each hop, add -L:
curl -sIL --resolve www.example.com:80:127.0.0.1 http://www.example.com/ | grep -Ei '^(HTTP|Location)'With --resolve, the redirected request to example.com is not covered by the override unless you add it too. If curl cannot reach the second hop, pass a second --resolve example.com:80:127.0.0.1 option.
Common errors
- Redirect loop (
ERR_TOO_MANY_REDIRECTS). This happens when a block redirects to a name that the same block, or another block, redirects back. A typical cause is the canonical name still listed in the redirect block'sserver_name. Check that the target of each redirect is served, not redirected, by its own block. - Duplicate names. If
www.example.comappears in two blocks on the same port,nginx -tprintsconflicting server name "www.example.com" on 0.0.0.0:80, ignored. Remove the name from one block. - Wrong block answers. If the
wwwname falls through to the default server, the name is missing from everyserver_name, or thelistenaddress differs. Test with theHostheader and read the access logs. - Lost path or query string. Writing
return 301 http://example.com;drops the path. Always append$request_uri. - Certificate mismatch on 443. The browser warns before it follows the redirect. Check with
openssl s_client -connect 127.0.0.1:443 -servername www.example.comand read the certificate subject names. - Stale browser cache. A mistaken 301 stays cached. Clear the cache or test with
curl.
Exercise
A site serves example.com and you want www.example.com to redirect to it over both HTTP and HTTPS. Your certificate covers both names. Which server blocks do you need, and what must each redirect preserve?
Show answer
Use a redirect block on port 80 for www.example.com (and optionally the bare name, to go to HTTPS), and a redirect block on port 443 with ssl_certificate and ssl_certificate_key for www.example.com, because the TLS handshake happens before Nginx can send the redirect. The canonical name needs its own serving block on port 443. Each redirect uses return 301 https://example.com$request_uri; so the path and query string are preserved. Remove www.example.com from the canonical block's server_name to avoid a conflicting name.
Exercise
After adding a redirect block, curl -I http://www.example.com/ keeps returning the redirect in your browser even after you removed it from the configuration, but curl shows 200. What is the likely cause, and how do you avoid it while testing?
Show answer
The browser cached the 301 response, which clients may keep without expiry. Clear the browser cache or use a private window. While testing, use return 302 or test with curl, and change to 301 once the behavior is correct.