Sub topic 10
Terminating TLS and redirecting HTTP to HTTPS
This chapter assumes you can already proxy a site to an upstream group, set forwarding headers, and test and reload Nginx. You also need a domain name that points at the server, and a certificate and private key for it. The key facts are below, then the configuration, the checks, and the usual failures.
What TLS termination means
TLS (Transport Layer Security) encrypts traffic between a client and a server. With TLS termination, Nginx is the endpoint of the encrypted connection. It decrypts each request and forwards it to the backend, usually as plain HTTP on a private network. It then encrypts the backend's response on the way out.
Terminating at the proxy has practical benefits:
- Certificates and keys live in one place instead of on every backend.
- Backends spend no CPU on handshakes.
- Nginx can read the decrypted request, so it can route, cache, and log it.
The cost is that the hop between Nginx and the backend is unencrypted. This is acceptable on a loopback address or a trusted private network. Across an untrusted network, use proxy_pass https://... and verify the backend certificate, or use a different design.
The redirect server block
The first block listens on port 80 and does one job: send every request to the HTTPS site.
server {
listen 80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}$request_uri is the original path plus query string, so /search?q=nginx survives the redirect. Using a fixed host name instead of $host has two advantages. It sends www visitors to one canonical name, and it prevents a request with a forged Host header from bouncing visitors to another domain. The topic example uses $host, which works but accepts any name that reaches this server block, so prefer the fixed name when you know it.
Status code choice:
| Code | Meaning | Effect on POST requests |
|---|---|---|
| 301 | Moved permanently | Browsers may change POST to GET |
| 308 | Permanent redirect | Method and body are preserved |
For ordinary websites 301 is fine. For APIs that receive POST requests on port 80, 308 is safer, though a client that sends a body over plain HTTP has already exposed it.
The HTTPS server block
The second block holds the certificate, the key, and the proxy rules.
server {
listen 443 ssl;
http2 on;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.fullchain.pem;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1h;
location / {
proxy_pass http://app_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Each directive does the following:
listen 443 ssl;turns on TLS for that port. Withoutssl, Nginx expects plain HTTP there and browsers fail with a protocol error.http2 on;enables HTTP/2 on Nginx 1.25.1 and later. On older versions, writelisten 443 ssl http2;instead.ssl_certificatemust point to the full chain: your certificate first, then the intermediate certificates. The root certificate is not needed.ssl_certificate_keyis the matching private key.ssl_protocolslimits the versions offered. TLS 1.0 and 1.1 are deprecated and should stay disabled.ssl_session_cache shared:SSL:10mstores session parameters in memory shared by all workers, so returning clients can resume a session without a full handshake. One megabyte holds roughly 4,000 sessions.
Leave the cipher list alone unless you have a compliance requirement. The defaults in current Nginx and OpenSSL packages are reasonable, and TLS 1.3 ciphers are not configured with ssl_ciphers.
Protect the key
The private key must be readable only by root. The Nginx master process runs as root and reads the key at startup and on reload, so the worker user needs no access.
sudo chown root:root /etc/ssl/private/example.com.key
sudo chmod 600 /etc/ssl/private/example.com.keyNever copy the key into a web-accessible directory or commit it to version control.
Telling the backend about HTTPS
The backend receives plain HTTP, so it cannot tell on its own that the client used HTTPS. X-Forwarded-Proto $scheme carries that fact. Inside the port 443 block $scheme is always https. The backend framework must be configured to trust the header, and only from the proxy's address. Otherwise the application will generate http:// links, set cookies without the Secure flag, or redirect to HTTPS itself.
That last case causes a classic failure. The backend sees an HTTP request, redirects to HTTPS, Nginx forwards the new request, and the backend again sees HTTP. The browser reports "too many redirects". The fix is to make the backend honor X-Forwarded-Proto, not to change Nginx.
Optional: HSTS
HSTS (HTTP Strict Transport Security) tells a browser to use HTTPS for your domain without even trying HTTP first. Add it inside the HTTPS server block:
add_header Strict-Transport-Security "max-age=31536000" always;The always parameter adds the header to error responses as well. Start with a short max-age, such as 300 seconds, and raise it once you are sure every subdomain and every path works over HTTPS. Browsers cache the policy, so a mistake cannot be undone quickly.
Trying it with a self-signed certificate
For a lab, create a short-lived self-signed certificate. Browsers will warn about it, but the Nginx configuration is the same as with a real certificate.
sudo openssl req -x509 -newkey rsa:2048 -nodes -days 30 \
-keyout /etc/ssl/private/example.com.key \
-out /etc/ssl/certs/example.com.fullchain.pem \
-subj "/CN=example.com" \
-addext "subjectAltName=DNS:example.com"For public sites, use a certificate from a trusted authority. Tools such as Certbot can obtain one and renew it automatically. After any renewal, Nginx must reload to pick up the new files.
Applying and verifying
Check the syntax, then reload without dropping connections:
sudo nginx -t && sudo systemctl reload nginxThen test the behavior from the outside:
curl -sI http://example.com/some/path?x=1
curl -sI https://example.com/
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | openssl x509 -noout -subject -datesThe first command should show 301 and a Location header with the same path and query. The second should show the backend's response over TLS. The third prints the certificate subject and its validity dates. The -servername option sends SNI (Server Name Indication), which tells Nginx which certificate to present when one IP address serves several names.
Common errors
| Symptom | Likely cause | What to do |
|---|---|---|
| `nginx -t` reports `key values mismatch` | Certificate and key come from different requests | Compare their public keys, or reissue the pair |
| Browser warns the chain is incomplete | Only the leaf certificate is configured | Concatenate leaf and intermediates into one file |
| "Too many redirects" | Backend redirects to HTTPS because it does not see the scheme | Make the backend trust `X-Forwarded-Proto` |
| Browser shows `ERR_SSL_PROTOCOL_ERROR` on 443 | `ssl` is missing on the `listen` line | Add `ssl` and reload |
| Page loads but images or scripts are blocked | Mixed content: the app emits `http://` URLs | Fix the app's base URL or scheme detection |
| Nginx fails to start with `Permission denied` on the key | Wrong ownership or path | Check the path and permissions, and run `nginx -t` as root |
| New certificate not served after renewal | Nginx still holds the old one in memory | Run `sudo systemctl reload nginx` |
To check that a certificate and key belong together, compare their public keys. The two outputs must be identical:
sudo openssl x509 -in /etc/ssl/certs/example.com.fullchain.pem -noout -pubkey | sha256sum
sudo openssl pkey -in /etc/ssl/private/example.com.key -pubout | sha256sumEdge cases to remember
- A request to the server's IP address, or to an unknown name, lands in the default server for that port. If it has no certificate, clients see a name mismatch. Define an explicit default that returns
444or uses a placeholder certificate. - Redirecting every port 80 request also breaks HTTP-01 certificate challenges unless you exempt
/.well-known/acme-challenge/. Put that path in its ownlocationon port 80, ahead of the redirect, or use a client that edits the config for you. - Redirecting with
returnruns before any proxying, so the backend never sees plain HTTP requests from outside.
Exercise
Users report "too many redirects" after you add TLS termination. The backend application redirects any request it sees as HTTP to HTTPS. Nginx already has proxy_set_header X-Forwarded-Proto $scheme; in the 443 block. What do you check next, and why?
Show answer
Check whether the backend is configured to trust X-Forwarded-Proto from the proxy's address. Nginx forwards the header correctly, but if the application ignores it, it still sees plain HTTP on every request, redirects to HTTPS, and loops. Enable proxy header trust in the application framework, limited to the proxy's IP, and confirm with curl -sI https://example.com/ that the loop is gone.
Exercise
Why does the redirect block use return 301 https://example.com$request_uri; and not a rewrite rule or a redirect to the site root?
Show answer
return is evaluated immediately and is cheaper and clearer than rewrite. $request_uri keeps the original path and query string, so deep links still work after the redirect. Sending everyone to the site root would lose the page the user asked for.