Sub topic 10
Enabling HTTPS and redirecting HTTP
HTTPS is HTTP carried inside a TLS (Transport Layer Security) session. TLS encrypts the traffic and lets the browser check that it is talking to the real server for a name. This chapter shows how to serve a site over TLS in Nginx, redirect plain HTTP to it, and fix the errors that come up most often.
I assume you can already write a server block, run nginx -t, and reload the service. Those topics come from earlier chapters. You should also know that a DNS name must point at your server before a certificate can be issued for it.
How TLS fits into a request
A browser connecting to https://example.com does the following before any HTTP is sent:
- It opens a TCP connection to port 443.
- It sends the name it wants (the SNI field, Server Name Indication) and a list of supported protocol versions and ciphers.
- Nginx replies with its certificate, which contains the public key and the names it is valid for. The certificate is signed by a certificate authority (CA).
- The browser checks the signature chain, the validity dates, and that the name matches.
- Both sides agree on session keys. After that, all HTTP traffic is encrypted.
Nginx needs two files for this:
- The certificate file. It holds your certificate, followed by any intermediate certificates from the CA. This combined file is often called the full chain.
- The private key file. It must stay secret. Only root should be able to read it.
Getting a certificate
You have three common options:
| Source | Use it for | Notes |
|---|---|---|
| Let's Encrypt (free CA, usually via Certbot) | Public sites | Certificates last 90 days or less and are renewed automatically |
| A commercial CA | Cases that need a specific vendor or validation level | You generate a key and a CSR (certificate signing request) and submit it |
| Self-signed certificate | Local testing | Browsers show a warning because no CA vouches for it |
For a quick local test, you can create a self-signed certificate with OpenSSL:
sudo openssl req -x509 -nodes -days 30 -newkey rsa:2048 \
-keyout /etc/ssl/private/example.com.key \
-out /etc/ssl/certs/example.com.crt \
-subj "/CN=example.com"
sudo chmod 600 /etc/ssl/private/example.com.keyThe -nodes option leaves the key without a passphrase. Nginx cannot prompt for a passphrase when it starts as a service, so a key with a passphrase would stop the service from starting.
For a public site, Certbot can obtain and renew a Let's Encrypt certificate. On Debian or Ubuntu, one way to install it and request a certificate is:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.comThe --nginx plugin edits your configuration for you. Read the changes it makes. The sections below explain what each directive does, so you can review or write them by hand. Certbot stores certificates in /etc/letsencrypt/live/example.com/, using fullchain.pem and privkey.pem.
The basic HTTPS configuration
The example below redirects all HTTP requests to HTTPS and serves the site over TLS.
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
root /var/www/example.com/html;
}Here is what each part does:
listen 443 ssl;tells Nginx to accept TLS connections on port 443 for this server block. Without thesslparameter, Nginx would speak plain HTTP on that port.ssl_certificatepoints to the certificate file, including the intermediates.ssl_certificate_keypoints to the private key that matches the certificate.return 301 https://$host$request_uri;sends a permanent redirect.$hostis the name the client asked for, and$request_uriis the original path and query string. The visitor lands on the same page, now over HTTPS.
After you edit the file, test and reload:
sudo nginx -t && sudo systemctl reload nginxThen check both behaviors from the command line:
curl -I http://example.com/
curl -I https://example.com/The first command should show 301 Moved Permanently and a Location header that starts with https://. The second should show a normal status such as 200 OK. For a self-signed certificate, add -k to the second command so curl accepts it.
Why `return` is better than `rewrite` for redirects
You can also write redirects with rewrite ... permanent, but return is simpler and faster. It stops processing immediately and does not evaluate a regular expression. Use return for whole-site redirects like this one.
Choosing 301 or 302
A 301 tells browsers and search engines the move is permanent. Browsers cache it, sometimes for a long time. If you test with a 301 and later change your mind, your own browser may keep following the old redirect. Use 302 while you experiment, then switch to 301 once the setup is final. If you need the request method preserved on a redirect, such as a POST, use 308 (permanent) or 307 (temporary). A 301 lets some clients change POST to GET.
Improving the TLS settings
Modern Nginx packages have reasonable defaults, but you should set the protocol versions explicitly and enable session reuse. Put these directives in the http context or inside the HTTPS server block:
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1h;ssl_protocolsdisables old, weak versions. TLS 1.0 and 1.1 are deprecated, and browsers have dropped them.ssl_session_cache shared:SSL:10mstores session parameters in memory shared by all worker processes. A returning client can resume a session without a full handshake. A 10 MB cache holds roughly 40,000 sessions.ssl_session_timeoutsets how long a cached session stays usable.
Leave the cipher list at its default unless you have a specific compliance requirement. The defaults in recent Nginx and OpenSSL versions are sensible, and a hand-written cipher string often does more harm than good.
Adding HSTS
HSTS (HTTP Strict Transport Security) is a response header that tells browsers to use HTTPS only for your site, even if the user types http://.
add_header Strict-Transport-Security "max-age=31536000" always;Add this only after you are sure HTTPS works for the domain and every subdomain you plan to cover. Browsers remember the header for the full max-age period, here one year. If your certificate expires during that time, users cannot click through the warning. The always parameter makes Nginx send the header on error responses too.
HTTP/2
HTTP/2 lets a browser send many requests over one connection. It requires TLS in practice, because browsers only use it over HTTPS. Enable it on the listen line:
listen 443 ssl http2;In Nginx 1.25.1 and later, the preferred form is a separate directive, and the http2 parameter on listen is deprecated:
listen 443 ssl;
http2 on;Check your version with nginx -v to see which form applies.
Several sites with HTTPS
Each HTTPS site gets its own server block, its own server_name, and its own certificate. Nginx uses SNI to choose the block, so many sites can share one IP address and port 443.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
root /var/www/example.com/html;
}
server {
listen 443 ssl;
server_name blog.example.org;
ssl_certificate /etc/ssl/certs/blog.example.org.crt;
ssl_certificate_key /etc/ssl/private/blog.example.org.key;
root /var/www/blog.example.org/html;
}A certificate can also cover several names. A wildcard certificate, such as *.example.com, covers every direct subdomain but not example.com itself unless that name is listed too.
Redirecting `www` and the bare domain
Pick one canonical name and redirect the other to it. This avoids duplicate content in search engines and splits no cookies. The certificate must include both names, because the redirect from the other name happens after the TLS handshake. A redirect to HTTPS cannot fix a name that the certificate does not cover.
server {
listen 80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
return 301 https://example.com$request_uri;
}The first block sends every HTTP request straight to the canonical HTTPS name in one hop. Avoid chains such as http://www to http:// to https://, because each hop costs a round trip.
Edge cases and common errors
- Redirect loop (
ERR_TOO_MANY_REDIRECTS). This happens when Nginx sits behind another proxy or load balancer that terminates TLS. Nginx sees plain HTTP on port 80 and redirects, the outer proxy forwards the request again, and the cycle repeats. Fix it by checking theX-Forwarded-Protoheader the outer proxy sends, or by letting the outer layer handle the redirect. nginx: [emerg] cannot load certificate. The path is wrong, the file is missing, or the certificate is not in PEM format. Check the path withls -l.key values mismatch. The key does not belong to the certificate. This often happens after a renewal when the old key is left in place.- Browser warns about an incomplete chain. The certificate file lacks the intermediate certificates. Use
fullchain.pemrather thancert.pem. - Certificate name mismatch. The name in the address bar is not in the certificate's list of names. Compare them with
openssl x509 -in cert.crt -noout -textand look at the Subject Alternative Name field. - Port 443 refused. Nginx is not listening, or a firewall blocks the port. Check with
sudo ss -tlnp | grep :443, and open the port in your firewall (for examplesudo ufw allow 'Nginx Full'on Ubuntu with UFW). - Renewed certificate not used. Nginx reads certificate files when it loads its configuration. After a renewal, run
sudo systemctl reload nginx. Certbot can do this with a deploy hook.
You can inspect what a server presents with OpenSSL:
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null \
| openssl x509 -noout -subject -issuer -datesThe -servername option sends the SNI name. Without it, you may see the certificate of the default server block rather than the one you want.
Protecting the private key
- Keep the key readable only by root:
chmod 600, owned by root. The Nginx master process runs as root and reads the key before it drops privileges in the worker processes. - Never put the key in a web-served directory or in version control.
- Use a separate key for each site where practical, so one leak does not affect every site.
Checklist
- Point DNS at the server and confirm that ports 80 and 443 are open.
- Obtain a certificate with the full chain.
- Add a
listen 443 sslblock withssl_certificateandssl_certificate_key. - Add a port 80 block that returns 301 to the HTTPS URL.
- Run
sudo nginx -t && sudo systemctl reload nginx. - Test with
curl -Ifor both schemes. - Set up automatic renewal and a reload after renewal.
- Add HSTS only when everything works.
Exercise
A visitor types http://www.example.com/shop?id=4 and your port 80 block contains return 301 https://example.com$request_uri;. What URL does the browser request next, and what must be true of the certificate for the visit to succeed without a warning?
Show answer
The browser requests https://example.com/shop?id=4, because $request_uri keeps the path and query string. The certificate Nginx presents for example.com must be valid, unexpired, signed by a trusted CA with the intermediate chain included, and list example.com as a name. If the visitor later reaches https://www.example.com directly, that name must be in the certificate as well.
Exercise
After renewing a certificate, browsers still show the old expiry date, although the new files are in place and nginx -t passes. What is the most likely cause and the fix?
Show answer
Nginx loads certificate files only when it reads its configuration, so the running workers still use the old certificate. Run sudo systemctl reload nginx to load the new files without dropping connections.
Exercise
Your site sits behind a cloud load balancer that terminates TLS and forwards plain HTTP to Nginx on port 80. After you add return 301 https://$host$request_uri; to that port 80 block, browsers report too many redirects. Why does this happen?
Show answer
Every request reaches Nginx on port 80 as plain HTTP, including ones the client made over HTTPS. Nginx redirects each one to HTTPS, the load balancer forwards the new request to port 80 again, and the loop never ends. Make the redirect conditional on the X-Forwarded-Proto header, or do the redirect on the load balancer.