Sub topic 13
Terminating HTTPS at the web server
This chapter assumes you have Nginx serving a PHP or Python application as described in earlier chapters. That means a working server block, Gunicorn or PHP-FPM behind it, and a domain name whose DNS record points at your server. You also need ports 80 and 443 open in the firewall and sudo access on a Debian/Ubuntu-style host.
What termination means
HTTPS is HTTP carried inside a TLS (Transport Layer Security) connection. TLS encrypts the traffic and proves to the client that it reached the server that owns the domain.
When you terminate TLS at the web server, Nginx does the cryptographic work. It holds the certificate and private key, decrypts incoming requests, and forwards plain HTTP to the application over a local socket or loopback port. The application never handles certificates.
This design has practical benefits:
- Certificates are managed and renewed in one place, whatever language the application uses.
- Nginx handles TLS efficiently, and the Gunicorn or PHP-FPM workers do not spend time on handshakes.
- The application only has to trust one local peer.
It has one cost. The application sees an HTTP request, so it cannot tell on its own that the client used HTTPS. Most of this chapter's gotchas come from that fact.
Getting a certificate
A certificate is a signed statement that a public key belongs to a domain. Browsers accept it only if it was issued by a certificate authority (CA) they trust. Let's Encrypt is a free CA that issues certificates through the ACME protocol. The certbot client automates the process.
Install it and request a certificate. The Nginx plugin proves you control the domain and edits your configuration:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.comThe files land in /etc/letsencrypt/live/example.com/:
| File | Contents | Use it for |
|---|---|---|
| `fullchain.pem` | Your certificate plus the intermediate certificates | `ssl_certificate` |
| `privkey.pem` | The private key | `ssl_certificate_key` |
| `cert.pem` | Your certificate only | Rarely needed |
| `chain.pem` | Intermediates only | OCSP stapling |
Use fullchain.pem, not cert.pem. Without the intermediates, some clients reject the connection even though browsers appear to work, because browsers cache intermediates and tools like curl or API clients often do not.
If you prefer to write the configuration yourself, request the certificate without letting certbot edit anything:
sudo mkdir -p /var/www/certbot
sudo certbot certonly --webroot -w /var/www/certbot -d example.com \
--deploy-hook "systemctl reload nginx"In webroot mode, certbot writes a challenge file under /var/www/certbot/.well-known/acme-challenge/. The Let's Encrypt servers fetch it over plain HTTP on port 80 to confirm you control the domain. The server block below serves that path.
The Nginx configuration
This configuration redirects all HTTP traffic to HTTPS, except the ACME challenge path. It then serves the application over TLS and passes the original scheme to Gunicorn:
server {
listen 80;
server_name example.com www.example.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
http2 on;
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;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
add_header Strict-Transport-Security "max-age=300" always;
location /static/ {
alias /srv/myapp/static/;
}
location / {
proxy_pass http://unix:/run/gunicorn/app.sock;
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;
}
}The main points:
listen 443 ssl;makes this block speak TLS. Thesslparameter is required. Without it Nginx would serve plain HTTP on port 443.http2 on;enables HTTP/2 and needs Nginx 1.25.1 or later. On older versions, writelisten 443 ssl http2;instead.ssl_protocols TLSv1.2 TLSv1.3;drops the obsolete TLS 1.0 and 1.1. Leavessl_ciphersat its default unless you have a compliance requirement. The defaults in current Nginx and OpenSSL are reasonable.ssl_session_cachelets returning clients resume a session without a full handshake. One megabyte holds about 4,000 sessions.return 301 https://$host$request_uri;preserves the hostname and the full path and query string. A redirect to a fixed URL would send every page to the home page.X-Forwarded-Proto $scheme;is nowhttpsfor requests that came through port 443. This is the line the application needs.
If you let certbot edit the file, it adds similar listen 443 ssl, certificate, and include /etc/letsencrypt/options-ssl-nginx.conf lines. Review the result with sudo nginx -t before reloading.
HSTS
The Strict-Transport-Security (HSTS) header tells browsers to use HTTPS for this domain without even trying HTTP. The example uses max-age=300 (five minutes) on purpose.
Telling the application about HTTPS
Because the proxied request is plain HTTP, the application has to learn the original scheme from a header. If it does not, it generates http:// links, sets cookies without the Secure flag, or redirects in a loop.
Python
Gunicorn recognizes X-Forwarded-Proto: https by default and sets wsgi.url_scheme to https. It only trusts the header from addresses listed in forwarded_allow_ips. The default is 127.0.0.1, which also covers Unix sockets. If Nginx runs on another host, pass --forwarded-allow-ips with that host's address. Do not use * unless the application port is unreachable from anywhere but your proxy, because otherwise any client could forge the header.
Frameworks add their own switch. In Django, for example, you set the following in settings.py:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")Set this only if Nginx always overwrites the header, as proxy_set_header does above. Otherwise a client could send its own header and make Django believe a plain HTTP request was secure.
PHP
For FastCGI, the snippets/fastcgi-php.conf file included in the earlier PHP chapter pulls in fastcgi.conf. That file contains fastcgi_param HTTPS $https if_not_empty;. Nginx sets $https to on on TLS connections, so PHP sees $_SERVER['HTTPS'] === 'on' with no extra work. A small test script confirms it:
<?php
echo "HTTPS: " . ($_SERVER['HTTPS'] ?? 'off') . "\n";If you hand-write FastCGI parameters instead of including that file, add fastcgi_param HTTPS $https if_not_empty; yourself.
Verifying and renewing
Check the configuration, reload, and test both the redirect and the TLS connection:
sudo nginx -t
sudo systemctl reload nginx
curl -I http://example.com/
curl -I https://example.com/
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null \
| openssl x509 -noout -subject -datesThe first curl should return 301 with a Location: https://... header. The second should return your application's normal status. The openssl command prints the certificate's subject and its notBefore and notAfter dates. The -servername option sends SNI (Server Name Indication), which Nginx uses to pick the right certificate when one IP address hosts several domains.
Let's Encrypt certificates last 90 days. The Debian certbot package installs a systemd timer that runs twice a day and renews certificates that are close to expiry. Confirm the timer exists and rehearse a renewal:
systemctl list-timers certbot.timer
sudo certbot renew --dry-run
sudo certbot certificatesNginx loads certificates when it starts or reloads, not on every connection. A renewed certificate on disk is not used until Nginx reloads, which is why the webroot example has --deploy-hook "systemctl reload nginx". The Nginx plugin sets up the reload for you.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Connection timeout on port 443 | Firewall or cloud security group blocks 443 | Open the port, then check with `ss -tlnp` that Nginx listens on it |
| Browser shows plain HTTP content or garbage on 443 | `ssl` missing from `listen 443` | Add the `ssl` parameter |
| `nginx -t` fails with a permission error on `privkey.pem` | Key is readable only by root and the test ran unprivileged | Run with `sudo`. The Nginx master process runs as root and reads the key before dropping privileges |
| Works in browsers, fails in `curl` or an API client | `ssl_certificate` points to `cert.pem` | Use `fullchain.pem` |
| Redirect loop (`ERR_TOO_MANY_REDIRECTS`) | The app forces HTTPS but never sees it | Send `X-Forwarded-Proto` and configure the framework to trust it |
| Browser warns of mixed content | The app generates `http://` URLs | Same fix as the redirect loop, or use relative URLs |
| Certificate expired | Renewal failed or Nginx was not reloaded | Run `certbot renew`, read `/var/log/letsencrypt/letsencrypt.log`, reload Nginx |
Exercise
After enabling HTTPS, your Python app redirects every request to https://example.com/login and the browser reports a redirect loop. Nginx terminates TLS and proxies to Gunicorn over a Unix socket. What two things do you check?
Show answer
First, check that the Nginx location / block sets proxy_set_header X-Forwarded-Proto $scheme;, so the app can see that the original request used HTTPS. Second, check that the application framework is configured to trust that header (for Django, SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")). Without both, the app sees plain HTTP on every request and keeps redirecting to HTTPS.
Exercise
Certbot renewed your certificate on disk 10 days ago, but openssl s_client still shows the old expiry date. Why, and what do you run?
Show answer
Nginx read the old certificate when it last started or reloaded and keeps using it from memory. Run sudo nginx -t and then sudo systemctl reload nginx. To prevent a repeat, add --deploy-hook "systemctl reload nginx" to the renewal configuration, or use the Nginx plugin, which reloads for you.