Serving a site over plain HTTP exposes logins, cookies and form data to anyone on the network path, and browsers mark such pages as Not secure. The fix is to redirect every HTTP request to HTTPS. In Nginx, that takes one line, but a production-grade setup does more: it redirects in a single hop to one canonical hostname, keeps Let’s Encrypt renewals working, rejects requests for hostnames you don’t host, uses modern TLS settings and tells browsers to use HTTPS on their own with HSTS.
This guide builds that configuration step by step. It works on Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux and the official Docker image.
Last tested: November 2026 with Nginx 1.30 (stable), Ubuntu 26.04 (Nginx 1.28), Ubuntu 24.04 (Nginx 1.24), Debian 13 (1.26) and Rocky Linux 10 (1.26). Every redirect, TLS setting and error message below comes from those tests.
Quick Answer
If you only need the redirect, put this server block in your site configuration, then run sudo nginx -t && sudo systemctl reload nginx:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://example.com$request_uri;
}
Two details make it better than the snippets you usually see. It redirects to a fixed hostname rather than $host, so http://www.example.com lands on https://example.com in one hop and a forged Host header can’t steer the redirect. And $request_uri keeps the full path and query string. The rest of this guide adds the security and performance settings around it.
301, 302, 307 or 308?
| Code | Permanent? | Keeps POST? | Use it for |
|---|---|---|---|
| 301 | Yes | No: browsers resend POST as GET | Websites. Search engines move rankings to the HTTPS URL. |
| 308 | Yes | Yes | APIs and form endpoints that receive POST, PUT or DELETE. |
| 302 / 307 | No | 302 no, 307 yes | Temporary moves only. Not for HTTPS redirects. |
Use 301 for websites. Browsers cache permanent redirects, so test with curl rather than a browser while you are still changing things.
Prerequisites
- Nginx installed and serving your site over HTTP
- An SSL/TLS certificate for every hostname you redirect to, including
www. A free Let’s Encrypt certificate works well; see how to install an SSL certificate in Nginx. - A user with sudo privileges
Step 1 of 6Check Your Nginx Version
HTTP/2 is configured differently depending on the version, so check it first:
nginx -v
Nginx 1.25.1 and newer (Ubuntu 26.04, Debian 13, RHEL 10 and the official packages) use a separate http2 on; directive, as in this guide. Ubuntu 24.04 ships Nginx 1.24, which stops with unknown directive "http2". On 1.24, drop the http2 on; lines and add http2 to the HTTPS listen lines instead:
listen 443 ssl http2;
listen [::]:443 ssl http2;
Don’t use the old form on newer versions. It still works there, but logs the "listen ... http2" directive is deprecated on every reload.
Step 2 of 6Set Shared TLS Settings Once
Put the TLS settings that apply to every site into one file in the http context instead of copying them into each server block. Files in /etc/nginx/conf.d/ are loaded there on all major distributions:
sudo nano /etc/nginx/conf.d/ssl-params.conf
# Shared TLS settings for every HTTPS site (http context)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
server_tokens off;
What these settings do:
- TLS 1.2 and 1.3 only. TLS 1.0 and 1.1 are deprecated and insecure. In our test, a TLS 1.1 client was refused with
alert protocol version. - Forward-secret AEAD ciphers only (ECDHE with AES-GCM or ChaCha20). Old CBC ciphers are refused. TLS 1.3 ciphers are always secure and need no configuration.
ssl_prefer_server_ciphers offlets each client pick the fastest cipher for its hardware, which is safe when every cipher on the list is strong. - A shared session cache. Returning visitors resume their TLS session instead of doing a full handshake, which saves a round trip and CPU on every reconnect. About 4,000 sessions fit in 1 MB, so 10 MB holds roughly 40,000.
- Session tickets off. Nginx doesn’t rotate session ticket keys on a schedule, so one key can protect sessions for weeks, which weakens forward secrecy. The session cache gives you resumption without that risk.
server_tokens offhides the exact Nginx version from headers and error pages.
Why the http context matters: Nginx uses the session cache settings of the default server on each listening port. In our test, with the cache set only inside the site’s server blocks and a catch-all default server (Step 3) on port 443, 0 out of 5 reconnects were resumed. With the settings in the http context, 5 out of 5 were.
Ubuntu and Debian: remove the duplicate lines
The nginx.conf shipped by Ubuntu and Debian already sets ssl_protocols and ssl_prefer_server_ciphers, so nginx -t fails with "ssl_prefer_server_ciphers" directive is duplicate. Ubuntu 24.04’s copy also still allows TLS 1.0 and 1.1. Comment out both lines:
sudo sed -i -E 's/^(\s*)(ssl_protocols|ssl_prefer_server_ciphers)/\1# \2/' /etc/nginx/nginx.conf
RHEL, Rocky Linux, AlmaLinux and the official Docker image don’t set these in nginx.conf, so skip this step there.
Step 3 of 6Reject Requests for Unknown Hostnames
Without a catch-all server, Nginx answers requests for any hostname, including requests to your bare IP address, with the first site it finds. Scanners and bots then get your real site and your redirects under hostnames you don’t control. A default server that drops these requests closes that gap:
sudo nano /etc/nginx/conf.d/00-default.conf
# Catch-all: close connections for hostnames this server doesn't host
server {
listen 80 default_server;
listen [::]:80 default_server;
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
server_name _;
ssl_reject_handshake on;
return 444;
}
return 444is Nginx’s special code to close the connection without sending a response.ssl_reject_handshake on(Nginx 1.19.4+) aborts the TLS handshake for unknown names, so this block needs no certificate and never exposes your real certificate to someone scanning IP addresses.
Only one server may be the default_server per port. Ubuntu and Debian ship one in /etc/nginx/sites-enabled/default, which causes a duplicate default server for 0.0.0.0:80. Disable it:
sudo rm /etc/nginx/sites-enabled/default
On RHEL-based systems, remove default_server from the example server block in /etc/nginx/nginx.conf if it is there. If a load balancer or monitoring tool checks your server by IP address, give it its own server_name or location, since the catch-all now drops those requests.
Step 4 of 6Create the Site Configuration
Now the site itself, as three server blocks. Replace example.com with your domain and point the certificate paths to your files. On Ubuntu and Debian, create it in /etc/nginx/sites-available/ and link it into sites-enabled; on RHEL-based systems, use /etc/nginx/conf.d/example.com.conf:
# 1. HTTP -> HTTPS for both names, straight to the canonical host
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
# Let's Encrypt HTTP-01 challenges stay on plain HTTP
location ^~ /.well-known/acme-challenge/ {
root /var/www/letsencrypt;
default_type "text/plain";
}
location / {
return 301 https://example.com$request_uri;
}
}
# 2. https://www.example.com -> https://example.com
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
return 301 https://example.com$request_uri;
}
# 3. The site itself
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
root /var/www/example.com;
index index.html index.php;
}
How the pieces work together:
- One hop, one canonical URL. The port 80 block sends both names straight to
https://example.com. A visitor tohttp://www.example.comgets one redirect, not two (http → https://www → https://example.com). That is faster and lets search engines consolidate on one URL. - Let’s Encrypt renewals keep working. HTTP-01 challenges are served from
/var/www/letsencryptover plain HTTP. With this setup, request and renew certificates withcertbot certonly --webroot -w /var/www/letsencrypt -d example.com -d www.example.com. - HSTS tells browsers to use HTTPS on their own for the next two years, so they skip the insecure first request and the redirect entirely. The
alwaysparameter adds the header to redirects and error pages too. It is also set on thewwwredirect, sowwwis covered as well. Read how to enable HSTS in Nginx before you addpreload, which is very hard to undo. - No
if, norewrite. A separate server block withreturnis the fastest and least error-prone way to redirect in Nginx.
Prefer www as the main address?
If https://www.example.com should be your canonical URL, redirect to it from port 80 and from https://example.com, and serve the site on the www name. Every variant still lands on https://www.example.com in a single hop, which we confirmed for http://example.com, http://www.example.com and https://example.com:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
location ^~ /.well-known/acme-challenge/ {
root /var/www/letsencrypt;
default_type "text/plain";
}
location / {
return 301 https://www.example.com$request_uri;
}
}
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
return 301 https://www.example.com$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
root /var/www/example.com;
index index.html index.php;
}
Ubuntu and Debian only, enable the site:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
Step 5 of 6Test the Configuration and Reload
Always check the syntax before reloading. A reload with a broken config keeps the old one running, but a restart would take your sites down:
sudo nginx -tsudo systemctl reload nginx
Step 6 of 6Verify the Redirects
Check the redirect, the number of hops and the HSTS header with curl. These are the results from our test server:
$ curl -sI "http://www.example.com/blog/?page=2" | grep -iE "^HTTP|^location"
HTTP/1.1 301 Moved Permanently
Location: https://example.com/blog/?page=2
$ curl -sIL -o /dev/null -w "%{num_redirects} redirect(s) -> %{url_effective}\n" http://www.example.com/
1 redirect(s) -> https://example.com/
$ curl -sI https://example.com/ | grep -iE "^HTTP|strict"
HTTP/2 200
strict-transport-security: max-age=63072000; includeSubDomains
Then confirm that old protocols are refused (expect an error, not a connection):
openssl s_client -connect example.com:443 -servername example.com -tls1_1 < /dev/null
For a full external check, run your domain through the SSL Labs server test.
Special Cases
Nginx behind a load balancer or Cloudflare
If a load balancer, CDN or Cloudflare (in Flexible mode) terminates TLS and talks to Nginx over plain HTTP, a normal port 80 redirect causes an endless redirect loop, because every request reaches Nginx on HTTP. Redirect based on the X-Forwarded-Proto header that the proxy sets:
server {
listen 80;
server_name app.example.com;
# The load balancer terminates TLS and sets X-Forwarded-Proto
if ($http_x_forwarded_proto = "http") {
return 301 https://app.example.com$request_uri;
}
root /var/www/app;
}
In our test, requests with X-Forwarded-Proto: http were redirected and requests with https were served normally. Only trust this header when Nginx can be reached exclusively through the proxy. With Cloudflare, the better fix is the Full (strict) SSL mode with a certificate on the origin, so the whole path is encrypted.
APIs: use 308 to keep the request method
Clients that follow a 301 change POST to GET and lose the request body. For API hostnames, use 308, which keeps the method and body. Our test POST stayed a POST after the redirect:
server {
listen 80;
listen [::]:80;
server_name api.example.com;
return 308 https://api.example.com$request_uri;
}
Better still, configure API clients to call https:// directly, since data sent in the first HTTP request has already crossed the network in clear text.
Common Mistakes to Avoid
- Using
if ($scheme = http)inside the HTTPS server block. It works, but evaluates on every request. A separate port 80 server block is cleaner and faster. - Redirecting to
https://$server_name$request_uri. With several names,$server_nameis always the first one, which may not be what you expect. Write the canonical hostname out. - Forgetting the certificate for
www. Visitors tohttps://www.example.comsee a certificate error before the redirect can happen. - Redirecting the ACME challenge path. Let’s Encrypt follows redirects, but then validation depends on your HTTPS server answering for that name, which it can’t before the first certificate is installed. The
location ^~ /.well-known/acme-challenge/block avoids that. - Enabling
ssl_staplingwith Let’s Encrypt. Let’s Encrypt shut down its OCSP service in August 2025, and its certificates no longer contain an OCSP URL, so stapling does nothing and Nginx logs a warning. Keep stapling only for CAs that still run OCSP. - Testing in a browser. Browsers cache 301 redirects and HSTS, so they hide your changes. Use
curl, or a private window.
Conclusion
A simple return 301 is enough to move visitors to HTTPS, but the complete setup takes only a few more lines. Redirect in one hop to a single canonical hostname, keep the ACME path open for renewals, drop requests for unknown hostnames, allow only TLS 1.2 and 1.3 with strong ciphers, put the session cache in the http context so resumption works, and send HSTS. Test with nginx -t before every reload, and verify with curl.
Next steps: enable HTTP/2 in Nginx, enable HSTS, and redirect other URLs in Nginx.
How did it make you feel?
