Chapter 3 · Lesson 5 of 22
Domains and HTTPS

Redirect HTTP to HTTPS (nginx and Caddy)

An HTTP to HTTPS redirect answers requests on port 80 with a permanent redirect to the same address on port 443, so visitors end up on the encrypted site.

By the end you will

Redirect HTTP to HTTPS with nginx and confirm it with curl, without locking yourself out via HSTS.

Time
18 min
Level
Beginner
Check
4 questions
You need
  • A site that already works over HTTPS

To redirect HTTP to HTTPS, answer requests on port 80 with a permanent redirect status to the same path on https://. Caddy does this by default; in nginx you add a small server block on port 80. Add the HSTS header only after HTTPS has been stable for a while.

A short history#

Redirects are as old as HTTP itself, but the plain-HTTP first request stayed a weak point. HSTS was standardized in 2012 so browsers could skip that request, and 308 arrived later as a method-preserving permanent redirect.

How it works#

The browser sends a request to port 80. Your server answers with a status code and a Location header, for example 301 and Location: https://example.com/page. The browser follows it and makes a new request, this time to port 443 over TLS. Because the first request is plain HTTP, the redirect itself can be read or altered by someone on the network. That gap is what HSTS closes.

HSTS (HTTP Strict Transport Security) is a header you send on HTTPS responses: Strict-Transport-Security: max-age=300. The browser stores it and, for the number of seconds in max-age, rewrites http:// for that site to https:// itself, without ever sending the plain request. Browsers ignore this header if it arrives over plain HTTP. The cost: if your HTTPS breaks, those browsers will not fall back to HTTP.

Status codes matter only a little here. 301 and 308 both mean “moved permanently”. A 301 lets some clients change a POST into a GET, while a 308 keeps the method and body. Temporary redirects (302, 307) tell the browser not to remember the move, which is useful while testing. Browsers cache permanent redirects hard.

Step 1: Redirect on port 80#

Caddy does this on its own. If your site has a hostname, Caddy gets a certificate and redirects port 80 to HTTPS with no configuration.

For nginx, add a server block on port 80:

nginx
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

listen [::]:80 makes it answer on IPv6 too. $host is the name the visitor used and $request_uri keeps the path and query. While testing, use return 302 first, and switch to 301 when you are sure. Test the file with sudo nginx -t, then sudo nginx -s reload. If you use Let’s Encrypt with the webroot method, leave the /.well-known/acme-challenge/ path served over HTTP (a location block before the redirect), or use a renewal method that does not need it.

Step 2: Add HSTS carefully#

Send the header from the HTTPS server block:

nginx
add_header Strict-Transport-Security "max-age=300" always;

always adds the header on error responses too. Five minutes (300 seconds) is a safe first value. Raise it in stages only when HTTPS has been stable. Avoid includeSubDomains unless every subdomain, including ones you forgot, serves valid HTTPS, and avoid preload until you understand it: preload puts your domain in a list shipped inside browsers, and removal takes a long time to reach users.

Comparing the options#

ApproachProtects the first visitRisk
Redirect onlyNo, the first request is plain HTTPLow
Redirect plus HSTSYes, after the first HTTPS visitA broken certificate locks visitors out until max-age ends
HSTS with preloadYes, even on the first visitVery slow to undo

Common misconceptions#

  • A redirect does not secure the first request. That request is still plain HTTP.
  • HSTS sent over plain HTTP does nothing. Browsers honor it only on HTTPS responses.
  • 301 and 302 are not only about search rankings. A 301 is cached hard by browsers and is the one that bites during testing.

When not to redirect#

Do not redirect for internal services that never get a certificate. Do not redirect in the origin when a CDN or proxy already ends TLS and talks plain HTTP to you, because that causes a loop. Do not close port 80 instead of redirecting, because certificate renewal often needs it.

Check it worked#

bash
curl -I http://example.com/page

Expect 301 (or 308) and location: https://example.com/page. The path must survive. Then:

bash
curl -I https://example.com/page

What you should see: 200 and, if you set it, a strict-transport-security header. If curl returns a redirect on the HTTPS URL too, the HTTPS server block is redirecting as well, which is a bug.

Edge cases and gotchas#

  • Behind a CDN or proxy that ends TLS. In Cloudflare Flexible mode, the CDN talks to your origin over plain HTTP, so an origin redirect to HTTPS makes every request redirect again: ERR_TOO_MANY_REDIRECTS. Use a full TLS mode between CDN and origin, or remove the origin redirect and let the CDN redirect.
  • An app plus a proxy both redirect. If the proxy ends HTTPS and the app sees HTTP, the app keeps redirecting. Make the proxy pass X-Forwarded-Proto and make the app trust it, or redirect in one layer only.
  • 301 is cached by browsers. If you test with 301 and the target is wrong, visitors may keep going there. Use 302 first.
  • HSTS is hard to undo. The browser remembers it until max-age runs out. With includeSubDomains it covers every subdomain, including internal tools on plain HTTP. With preload, removal takes a long time.
  • POST bodies and APIs. A client that posts to http:// may lose its body on a 301. Use 308 for APIs, and fix clients to call https:// directly.
  • Port 80 must stay open. Closing it makes http:// links fail, and it breaks Let’s Encrypt HTTP-01 issuing and renewal.
  • Mixed content. An HTTPS page that loads http:// scripts or images has those blocked or flagged. Change them to https://.

Troubleshooting#

SymptomLikely causeFix
ERR_TOO_MANY_REDIRECTSProxy or CDN talks HTTP to an origin that redirectsUse full TLS to the origin, or redirect in one layer
curl: (7) Failed to connect to example.com port 80Port 80 closed or nothing listeningOpen port 80 in the firewall and add the server block
Redirect works but HTTPS failsPort 443 closed or no certificateCheck the firewall and sudo certbot certificates
NET::ERR_CERT_COMMON_NAME_INVALID after redirectCertificate does not list the nameReissue with every name you serve
Redirect goes to https://_/...Used $server_name of a default block, not $hostUse $host or write the name explicitly
Browser forces HTTPS and shows an HSTS errorHSTS was cached and HTTPS is brokenFix the certificate; wait for max-age if you must go back
Mixed content warningsPage links to http:// resourcesUpdate the links to https://
curl: (7) on port 80 after you closed itPort 80 is shut, so http:// links failKeep port 80 open and redirect
Redirect works in curl, not in the browserBrowser holds an older cached 301Test in a private window, use 302 while testing

Real-world scenario#

Rin runs an API and a website behind one nginx. After she adds the redirect, the website is fine but a partner’s script, which posts to http://api.example.com/orders, starts failing. With a 301, that client turned the POST into a GET.

bash
curl -i -X POST http://api.example.com/orders -d 'a=1'

The response is a 301 and her partner’s client retries without the body. She changes the API block to return 308, and the partner fixes the URL to https://. Later she turns on Cloudflare in Flexible mode and the site immediately shows a loop: the CDN fetches from the origin over HTTP and the origin redirects to HTTPS each time. She switches the origin mode to one that uses TLS to the origin, and the loop ends. The proxy side is in what is a reverse proxy, and certificate setup in nginx reverse proxy with certbot.

Quick reference#

TaskSetting
nginx redirectreturn 301 https://$host$request_uri;
Keep POST bodiesuse return 308
While testingreturn 302
HSTS, first valueadd_header Strict-Transport-Security "max-age=300" always;
Caddyautomatic, no config
Check HTTPcurl -I http://example.com/page
Check HTTPScurl -I https://example.com/page

Security and safety notes#

  • Do not set a long HSTS max-age, includeSubDomains or preload until HTTPS has been stable for a while.
  • Keep a way in (SSH or console access) before editing server config, and run sudo nginx -t before reloading.

Next#

Cover many subdomains with one certificate in Wildcard certificates, explained.

Check what you learned4 questions
1When is a 308 redirect a better choice than a 301?
2Why start HSTS with a short max-age?
3You get a too many redirects error behind a proxy that ends HTTPS. What is a likely cause?
4Cloudflare is in Flexible mode and your origin redirects HTTP to HTTPS. What do visitors see?

Frequently asked questions

Do I need to set up the redirect in Caddy?

No. Caddy redirects HTTP to HTTPS on its own for sites it serves with a certificate.

Can I undo HSTS?

Only slowly. Browsers remember the header until its max-age runs out, so a mistake can lock visitors out for that whole time.

Does the HSTS header work if I send it on plain HTTP?

No. Browsers ignore Strict-Transport-Security on HTTP responses and honor it only over HTTPS, so you still need the redirect for first visits.

Should I redirect or just close port 80?

Redirect. Closing port 80 makes http:// links fail with a connection error instead of landing on your HTTPS site. Port 80 is also needed for the Let's Encrypt HTTP-01 check.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios