Sub topic 11
Redirecting HTTP to HTTPS and enabling HSTS
This chapter assumes you already have a working certificate from Certbot, the files under /etc/letsencrypt/live/example.com/, and an nginx server that answers on port 443. You should be comfortable editing nginx configuration and reading HTTP headers with curl. Here you will make HTTPS the only way into the site, then tell browsers to remember that choice.
Why a certificate is not enough
A certificate only protects visitors who connect over HTTPS. Someone who types example.com into a browser, or follows an old http:// link, starts on port 80 in plain text. Until the server answers with something better, that first request can be read or altered on the network. Two mechanisms close the gap:
- A redirect answers every plain HTTP request with a pointer to the HTTPS address.
- HSTS (HTTP Strict Transport Security) is a response header. It tells a browser to use HTTPS for your host from now on, without trying HTTP first.
The redirect fixes the problem for every client. HSTS removes the plain HTTP request for returning browsers.
The redirect
Put a dedicated server block on port 80 whose only job is to redirect.
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}Three details matter here.
returnis cheaper and clearer than arewriterule. It stops processing at once and needs no regular expression.$request_uriholds the original path and query string, sohttp://www.example.com/blog?page=2lands onhttps://example.com/blog?page=2. Writing onlyhttps://example.comwould send every visitor to the home page.- The target uses a fixed name. That makes
example.comthe canonical host, so thewwwname and the bare name never end up as two separate sites. If you serve many hostnames, use$hostinstead:return 301 https://$host$request_uri;.
Choosing the status code
| Code | Meaning | Method on the follow-up request |
|---|---|---|
| 301 | Moved permanently | Browsers may change POST to GET |
| 308 | Permanent redirect | Method and body are preserved |
| 302 / 307 | Temporary | Not cached as permanent; avoid for a lasting move |
301 is the common choice and works well for page visits. If API clients send POST requests to your plain HTTP address, 308 keeps them from turning into GET requests. Fixing those clients to use HTTPS is better still.
Validation still works
HTTP-01 validation requests http://example.com/.well-known/acme-challenge/<token> on port 80. Let's Encrypt follows redirects, but only to ports 80 and 443. A blanket redirect to HTTPS therefore does not break renewals. The validator does not check the certificate on a redirect to port 443, so an expired certificate can still be renewed. Port 80 must stay open in the firewall and in your cloud security group, because renewal depends on it.
The HTTPS server block
The second block serves the site and sends the HSTS header.
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=31536000" always;
root /var/www/html;
}Always test before reloading, so a typo cannot take the site down:
sudo nginx -t && sudo systemctl reload nginxThe following diagram shows what a client sees on its first and later visits.
How HSTS works
The header has this form:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preloadmax-ageis the number of seconds the browser should remember the policy. 31536000 is one year. Every HTTPS response refreshes the timer.includeSubDomainsextends the policy to every subdomain, such asmail.example.comordev.example.com.preloadsignals that you want the domain added to the preload lists shipped inside browsers.
Browsers ignore this header when it arrives over plain HTTP. It only counts when it comes over a valid HTTPS connection. That is why the redirect is still needed: HSTS cannot protect the very first visit.
While a policy is active, the browser also refuses to let users click through certificate warnings for that host. An expired certificate then produces a hard failure instead of a warning. This is a security benefit, and it is also why the renewal chapters matter.
The `always` parameter and header inheritance
By default, nginx adds headers only to successful and redirect responses (200, 201, 204, 206, 301, 302, 303, 304, 307, 308). With always, the header also appears on error pages such as 404 and 500. Without it, a browser that first sees your site through an error page does not learn the policy.
A second gotcha: add_header directives are inherited from the enclosing level only if the current level defines none of its own. If a location block contains any add_header line, it silently drops the HSTS header set at the server level. Repeat the HSTS line in that location, or put all headers in one file and include it at each level.
Roll out HSTS in stages
A long max-age is hard to undo. If you later need HTTP, for example because you broke your certificate renewal, every browser that has the policy keeps forcing HTTPS until the timer runs out. Increase the value in steps:
- Start with
max-age=300(five minutes) and confirm that everything works. - Move to
max-age=86400(one day), then to one week. - After a month without problems, use
max-age=31536000. - Add
includeSubDomainsonly after you have confirmed that every subdomain, including internal tools, serves valid HTTPS.
Verify with curl
Check the redirect first. The query string should survive.
curl -sI "http://example.com/blog?page=2" | grep -iE '^(HTTP|location)'Expected output:
HTTP/1.1 301 Moved Permanently
Location: https://example.com/blog?page=2Then check the header, including on an error page:
curl -sI https://example.com/ | grep -i strict-transport-security
curl -sI https://example.com/no-such-page | grep -iE '^(HTTP|strict-transport)'If the second command shows a 404 but no HSTS header, the always parameter is missing.
Common errors
- Redirect loop (
ERR_TOO_MANY_REDIRECTS). This happens when a TLS-terminating proxy or CDN in front of nginx talks to it over HTTP, and nginx redirects those requests to HTTPS again. Terminate TLS in one place, or redirect based on theX-Forwarded-Protoheader. - Redirect lands on the wrong host. A hard-coded name in
returncan send a user fromstaging.example.comto production. Use$hostwhen one block serves several names. - HSTS header missing on some pages. The cause is usually
add_headerinheritance, described above. - Renewal fails after adding the redirect. Check that port 80 is still reachable from the internet and that no
locationrule blocks/.well-known/acme-challenge/.
Exercise
You add add_header Strict-Transport-Security "max-age=31536000"; to the HTTPS server block. A browser visiting a 404 page on your site does not receive the header, and /admin also loses it after you add add_header X-Frame-Options DENY; inside location /admin. What two changes fix both problems?
Show answer
Add the always parameter to the HSTS line, so nginx sends it on error responses such as 404. Then repeat the HSTS add_header ... always; line inside location /admin (or move all headers into a shared file included at each level). A location block that defines its own add_header does not inherit the server-level headers.
Exercise
Why does a site need the port 80 redirect even after HSTS is enabled, and why should port 80 stay open in the firewall?
Show answer
Browsers only accept the HSTS header over HTTPS, so a first-time visitor, or one whose policy has expired, still sends a plain HTTP request. The redirect handles that request. Port 80 must also stay open because HTTP-01 validation during certificate renewal uses it.