# 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.

URL: https://levelrail.com/learn/domains-https/redirect-http-to-https-explained/
Updated: 2026-11-27

To redirect HTTP to HTTPS, answer requests on port 80 with a permanent [redirect status](https://levelrail.com/learn/glossary/#http-status-code)) 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](https://levelrail.com/learn/glossary/#https)) 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

| Approach | Protects the first visit | Risk |
| --- | --- | --- |
| Redirect only | No, the first request is plain HTTP | Low |
| Redirect plus HSTS | Yes, after the first HTTPS visit | A broken certificate locks visitors out until `max-age` ends |
| HSTS with preload | Yes, even on the first visit | Very 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

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `ERR_TOO_MANY_REDIRECTS` | Proxy or CDN talks HTTP to an origin that redirects | Use full TLS to the origin, or redirect in one layer |
| `curl: (7) Failed to connect to example.com port 80` | Port 80 closed or nothing listening | Open port 80 in the firewall and add the server block |
| Redirect works but HTTPS fails | Port 443 closed or no certificate | Check the firewall and `sudo certbot certificates` |
| `NET::ERR_CERT_COMMON_NAME_INVALID` after redirect | Certificate does not list the name | Reissue with every name you serve |
| Redirect goes to `https://_/...` | Used `$server_name` of a default block, not `$host` | Use `$host` or write the name explicitly |
| Browser forces HTTPS and shows an HSTS error | HSTS was cached and HTTPS is broken | Fix the certificate; wait for `max-age` if you must go back |
| Mixed content warnings | Page links to `http://` resources | Update the links to `https://` |
| `curl: (7)` on port 80 after you closed it | Port 80 is shut, so `http://` links fail | Keep port 80 open and redirect |
| Redirect works in curl, not in the browser | Browser holds an older cached 301 | Test 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](https://levelrail.com/learn/deploy-operate/what-is-a-reverse-proxy/)), and certificate setup in [nginx reverse proxy with certbot](https://levelrail.com/learn/domains-https/nginx-reverse-proxy-with-certbot/)).

## Quick reference

| Task | Setting |
| --- | --- |
| nginx redirect | `return 301 https://$host$request_uri;` |
| Keep POST bodies | use `return 308` |
| While testing | `return 302` |
| HSTS, first value | `add_header Strict-Transport-Security "max-age=300" always;` |
| Caddy | automatic, no config |
| Check HTTP | `curl -I http://example.com/page` |
| Check HTTPS | `curl -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.

## Related lessons

- [HTTPS and Let's Encrypt](https://levelrail.com/learn/domains-https/https-and-lets-encrypt/)): the certificate behind the redirect
- [Redirect www to the bare domain](https://levelrail.com/learn/domains-https/redirect-www-to-the-bare-domain/)): the other redirect rule
- [Automatic HTTPS with Caddy](https://levelrail.com/learn/domains-https/automatic-https-with-caddy/)): redirects without configuration
- [Fix 502 bad gateway](https://levelrail.com/learn/deploy-operate/fix-502-bad-gateway/)): what to check when the proxy returns errors

## Next

Cover many subdomains with one certificate in [Wildcard certificates, explained](https://levelrail.com/learn/domains-https/wildcard-certificates-explained/)).

## 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

- [Caddy docs, automatic HTTPS](https://caddyserver.com/docs/automatic-https)
- [MDN, Strict-Transport-Security](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security)
