Short answer

Make three server blocks: one on port 80 for both names, and one on 443 for www, each with return 301 https://example.com$request_uri;. The third, on 443 for example.com, serves the site. The certificate must cover www.example.com too. Run sudo nginx -t, then sudo systemctl reload nginx.

Tested on Ubuntu 26.04 and 24.04, two separate runs. On 24.04? 2 sections differ, each step marked “On Ubuntu 24.04” right under it: Step 1: See what the four addresses answer now, Step 3: Replace certbot’s redirect with three server blocks. Everything that differed

Before you start

  • An Ubuntu 26.04 or 24.04 server with Nginx, a site for example.com and www.example.com, and a certificate from certbot (Let’s Encrypt for Nginx). Put your domain in place of example.com everywhere below.
  • DNS records for both names point at the server. A redirect cannot help a name that does not reach the server.
  • Pick ONE address for the site. This page keeps https://example.com and sends the other three there. To keep www instead, see www as the main name.

Step 1: See what the four addresses answer now

There are four ways to type the address: with and without www, over http and https. This loop asks for each one and prints the answer and where it redirects to. Run it on the server, or on your own computer:

Server
$ for u in http://example.com http://www.example.com https://example.com https://www.example.com; do curl -sS -o /dev/null -w "$u  %{http_code}  %{redirect_url}\n" $u; donehttp://example.com  301  https://example.com/http://www.example.com  404https://example.com  200curl: (60) SSL: no alternative certificate subject name matches target hostname 'www.example.com'More details here: https://curl.se/docs/sslcerts.html curl failed to verify the legitimacy of the server and therefore could notestablish a secure connection to it. To learn more about this situation andhow to fix it, please visit the webpage mentioned above.https://www.example.com  000
Output hidden (10 lines)

This server got its certificate with certbot --nginx -d example.com, without www. That is common, and it leaves www broken twice: http://www gets 404, from the block certbot added, and https://www fails because the certificate does not name www. A browser shows a full-page certificate warning there. No redirect can fix that, because the browser checks the certificate before Nginx can send anything.

On Ubuntu 24.04

The curl on 24.04 (8.5) words its certificate error a little differently: target host name and web page, where the curl on 26.04 (8.18) prints target hostname and webpage. The meaning is the same.

Step 2: Make sure the certificate covers www

Server
$ sudo certbot certificatesSaving debug log to /var/log/letsencrypt/letsencrypt.log - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Found the following certs:  Certificate Name: example.com    Serial Number: <serial>    Key Type: ECDSA    Domains: example.com    Expiry Date: 2027-02-17 16:20:48+00:00 (VALID: 89 days)    Certificate Path: /etc/letsencrypt/live/example.com/fullchain.pem    Private Key Path: /etc/letsencrypt/live/example.com/privkey.pem- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Output hidden (12 lines)

Look at the Domains: line. If both names are on it, go to step 3. If only the bare name is, ask certbot for both. It sees the existing certificate and offers to expand it; answer E:

Server
$ sudo certbot --nginx -d example.com -d www.example.comSaving debug log to /var/log/letsencrypt/letsencrypt.log - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -You have an existing certificate that contains a portion of the domains yourequested (ref: /etc/letsencrypt/renewal/example.com.conf) It contains these names: example.com You requested these names for the new certificate:example.com, www.example.com. Do you want to expand and replace this existing certificate with the newcertificate?- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -(E)xpand/(C)ancel: ERenewing an existing certificate for example.com and www.example.com Successfully received certificate.Certificate is saved at: /etc/letsencrypt/live/example.com/fullchain.pemKey is saved at:         /etc/letsencrypt/live/example.com/privkey.pemThis certificate expires on 2027-02-17.These files will be updated when the certificate renews.Certbot has set up a scheduled task to automatically renew this certificate in the background. Deploying certificateSuccessfully deployed certificate for example.com to /etc/nginx/sites-enabled/example.comSuccessfully deployed certificate for www.example.com to /etc/nginx/sites-enabled/example.comYour existing certificate has been successfully renewed, and the new certificate has been installed. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -If you like Certbot, please consider supporting our work by: * Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate * Donating to EFF:                    https://eff.org/donate-le- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Output hidden (34 lines)
Server
$ sudo certbot certificatesSaving debug log to /var/log/letsencrypt/letsencrypt.log - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Found the following certs:  Certificate Name: example.com    Serial Number: <serial>    Key Type: ECDSA    Domains: example.com www.example.com    Expiry Date: 2027-02-17 16:21:38+00:00 (VALID: 89 days)    Certificate Path: /etc/letsencrypt/live/example.com/fullchain.pem    Private Key Path: /etc/letsencrypt/live/example.com/privkey.pem- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Output hidden (12 lines)

The certificate keeps its name and its files, so nothing that points at /etc/letsencrypt/live/example.com/ has to change. Now look at the four addresses again:

Server
$ for u in http://example.com http://www.example.com https://example.com https://www.example.com; do curl -sS -o /dev/null -w "$u  %{http_code}  %{redirect_url}\n" $u; donehttp://example.com  301  https://example.com/http://www.example.com  301  https://www.example.com/https://example.com  200https://www.example.com  200
Output hidden (4 lines)

Everything works, but certbot’s redirect only moves http to https and keeps the name. http://www goes to https://www, and https://www serves the whole site a second time. Search engines see two copies of every page. Step 3 sends all of them to one address.

Step 3: Replace certbot’s redirect with three server blocks

Keep a copy of the current file first, so you can go back (undo):

Server
$ sudo cp /etc/nginx/sites-available/example.com ~/example.com.certbot

This is what certbot made of the site’s file. One block serves both names on 443. The other, on port 80, redirects with if ($host = …) and keeps the name the visitor typed ($host):

Server
$ cat /etc/nginx/sites-available/example.comserver {    server_name example.com www.example.com;    root /var/www/example.com;    index index.html;     listen 443 ssl; # managed by Certbot    listen [::]:443 ssl ipv6only=on; # managed by Certbot    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot   }server {    if ($host = www.example.com) {        return 301 https://$host$request_uri;    } # managed by Certbot      if ($host = example.com) {        return 301 https://$host$request_uri;    } # managed by Certbot      listen 80;    listen [::]:80;    server_name example.com www.example.com;    return 404; # managed by Certbot    }
Output hidden (35 lines)
On Ubuntu 24.04

Certbot 2.9.0 on 24.04 wrote the two listen … 443 lines of the main block the other way round, [::]:443 ssl ipv6only=on first. Keep whichever order your file has.

Write the file again with three plain blocks. The certificate lines are the ones certbot wrote, and both HTTPS blocks need them. Use sudo nano and paste the part between the EOF lines if you prefer:

Server
$ sudo tee /etc/nginx/sites-available/example.com > /dev/null <<'EOF'# 1. HTTP, both names: go to https://example.comserver {    listen 80;    listen [::]:80;    server_name example.com www.example.com;    return 301 https://example.com$request_uri;} # 2. HTTPS, www: go to https://example.comserver {    listen 443 ssl;    listen [::]:443 ssl;    server_name www.example.com;    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;    include /etc/letsencrypt/options-ssl-nginx.conf;    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;    return 301 https://example.com$request_uri;} # 3. HTTPS, example.com: the siteserver {    listen 443 ssl;    listen [::]:443 ssl;    server_name example.com;    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;    include /etc/letsencrypt/options-ssl-nginx.conf;    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;    root /var/www/example.com;    index index.html;}EOF
  • Both redirects name the target, https://example.com. Do not use $host there: it is the name the visitor typed, so www would stay www.
  • $request_uri is the path and the query string, so /docs/?page=2 arrives at the same page.
  • Every block that listens on 443 needs certificate lines, the redirect-only block too. The TLS handshake comes first, before Nginx reads the request.
  • Put your site’s own lines in block 3: the root, any location blocks, proxy_pass for an app.
Server
$ sudo nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful
Output hidden (2 lines)
Server
$ sudo systemctl reload nginx

Step 4: Check every address

Server
$ for u in http://example.com http://www.example.com https://example.com https://www.example.com; do curl -sS -o /dev/null -w "$u  %{http_code}  %{redirect_url}\n" $u; donehttp://example.com  301  https://example.com/http://www.example.com  301  https://example.com/https://example.com  200https://www.example.com  301  https://example.com/
Output hidden (4 lines)

Three addresses answer 301 to https://example.com/, and only that one serves the page. In the test the same four answers came back when the addresses were asked for from another network. The path and the query string are kept:

Server
$ curl -sI 'http://www.example.com/docs/?page=2' | grep -i '^location'Location: https://example.com/docs/?page=2
Output hidden (1 line)

And it takes one hop. -L follows the redirects; there is one 301, then the page. A chain such as http://www → https://www → https://example.com costs the visitor an extra round trip:

Server
$ curl -sIL http://www.example.com | grep -iE '^(HTTP|location)'HTTP/1.1 301 Moved PermanentlyLocation: https://example.com/HTTP/1.1 200 OK
Output hidden (3 lines)

Step 5: Check that renewal still works

The port-80 block now redirects everything, including the address Let’s Encrypt asks for when it checks the domain. Renewal still works. At renewal time certbot puts its own answer for that address at the top of the block, before the return. Prove it with a dry run:

Server
$ sudo certbot renew --dry-runSaving debug log to /var/log/letsencrypt/letsencrypt.log - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Processing /etc/letsencrypt/renewal/example.com.conf- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Account registered.Simulating renewal of an existing certificate for example.com and www.example.com - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Congratulations, all simulated renewals succeeded:  /etc/letsencrypt/live/example.com/fullchain.pem (success)- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Output hidden (12 lines)

certbot takes its lines out again afterwards. In the test the file was byte for byte the one written in step 3. The certificate path is the same as before, so the renewed certificate is used after the reload certbot does.

www as the main name instead

Swap the names: the port-80 block and the bare-name HTTPS block redirect to https://www.example.com, and the www block serves the site. The certificate lines stay the same, because the one certificate covers both names:

Server
$ sudo tee /etc/nginx/sites-available/example.com > /dev/null <<'EOF'# 1. HTTP, both names: go to https://www.example.comserver {    listen 80;    listen [::]:80;    server_name example.com www.example.com;    return 301 https://www.example.com$request_uri;} # 2. HTTPS, the bare name: go to https://www.example.comserver {    listen 443 ssl;    listen [::]:443 ssl;    server_name example.com;    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;    include /etc/letsencrypt/options-ssl-nginx.conf;    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;    return 301 https://www.example.com$request_uri;} # 3. HTTPS, www.example.com: the siteserver {    listen 443 ssl;    listen [::]:443 ssl;    server_name www.example.com;    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;    include /etc/letsencrypt/options-ssl-nginx.conf;    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;    root /var/www/example.com;    index index.html;}EOF
Server
$ sudo nginx -t && sudo systemctl reload nginxnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful
Output hidden (2 lines)
Server
$ for u in http://example.com http://www.example.com https://example.com https://www.example.com; do curl -sS -o /dev/null -w "$u  %{http_code}  %{redirect_url}\n" $u; donehttp://example.com  301  https://www.example.com/http://www.example.com  301  https://www.example.com/https://example.com  301  https://www.example.com/https://www.example.com  200
Output hidden (4 lines)

Either choice is fine for search engines. What matters is that only one address serves the page and the others send a permanent redirect to it.

Forms and APIs: 301 or 308

A 301 is right for pages. But a form or an API client that sends a POST to an old address loses its data: after a 301, browsers and curl send the next request as a GET. In the test a POST went to http://www.example.com/ with a User-Agent of its own (-A form-test), so its lines are easy to find in the access log among other visitors’ requests:

Server
$ curl -s -o /dev/null -L -A form-test -d 'name=test' http://www.example.com/
Server
$ sudo grep form-test /var/log/nginx/access.log | tail -n 2 | cut -d'"' -f2,3POST / HTTP/1.1" 301 178GET / HTTP/1.1" 200 48
Output hidden (2 lines)

The POST got the 301, and only a GET arrived at the site. A 308 is also permanent, but it tells the client to repeat the same method with the same body. Change both redirects to 308:

Server
$ sudo sed -i 's/return 301/return 308/' /etc/nginx/sites-available/example.com
Server
$ sudo nginx -t && sudo systemctl reload nginxnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful
Output hidden (2 lines)
Server
$ curl -s -o /dev/null -L -A form-test -d 'name=test' http://www.example.com/
Server
$ sudo grep form-test /var/log/nginx/access.log | tail -n 2 | cut -d'"' -f2,3POST / HTTP/1.1" 308 180POST / HTTP/1.1" 405 166
Output hidden (2 lines)

Now the POST arrives as a POST. The test site is plain HTML, so Nginx answers it 405 Not Allowed; your app gets the data. Use 308 when anything posts to the old addresses, and 301 otherwise. Every browser in use today follows both. This page goes back to 301 for the rest:

Server
$ sudo sed -i 's/return 308/return 301/' /etc/nginx/sites-available/example.com && sudo systemctl reload nginx

Optional: tell browsers to use HTTPS every time (HSTS)

The redirect still lets the first request go out over plain http, where it can be read or changed on the way. The Strict-Transport-Security header tells a browser to use https for this name by itself from then on. This adds it to the main HTTPS block only, under its server_name example.com; line:

Server
$ sudo sed -i '/server_name example.com;/a\    add_header Strict-Transport-Security "max-age=31536000" always;' /etc/nginx/sites-available/example.com
Server
$ sudo nginx -t && sudo systemctl reload nginxnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful
Output hidden (2 lines)
Server
$ curl -sI https://example.com | grep -i strictStrict-Transport-Security: max-age=31536000
Output hidden (1 line)

“Too many redirects”: the redirect loop

The usual cause is a return 301 in the block that serves the main name, often because one HTTPS block lists both names. In the test the file was written like this:

Server
$ sudo tee /etc/nginx/sites-available/example.com > /dev/null <<'EOF'server {    listen 80;    listen [::]:80;    server_name example.com www.example.com;    return 301 https://example.com$request_uri;} server {    listen 443 ssl;    listen [::]:443 ssl;    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;    include /etc/letsencrypt/options-ssl-nginx.conf;    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;    return 301 https://example.com$request_uri;    root /var/www/example.com;    index index.html;}EOF

nginx -t cannot see the problem, so the test passes:

Server
$ sudo nginx -t && sudo systemctl reload nginxnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful
Output hidden (2 lines)

But https://example.com now redirects to itself. A browser gives up with “too many redirects” (ERR_TOO_MANY_REDIRECTS in Chrome). curl stops at the limit you give it:

Server
$ curl -sSIL --max-redirs 5 https://example.com 2>&1 | grep -iE '^(HTTP|location|curl)'curl: (47) Maximum (5) redirects followedHTTP/1.1 301 Moved PermanentlyLocation: https://example.com/HTTP/1.1 301 Moved PermanentlyLocation: https://example.com/HTTP/1.1 301 Moved PermanentlyLocation: https://example.com/HTTP/1.1 301 Moved PermanentlyLocation: https://example.com/HTTP/1.1 301 Moved PermanentlyLocation: https://example.com/HTTP/1.1 301 Moved PermanentlyLocation: https://example.com/
Output hidden (13 lines)

The fix is step 3: the block that serves the main name has no return, and the www name has its own block. A loop can also come from a proxy in front of the server. If Cloudflare’s SSL mode is “Flexible”, it asks your server over http, your server redirects to https, and Cloudflare asks over http again. Set it to “Full (strict)”.

Undo

Put back the file you saved in step 3, then test and reload:

Server
$ sudo cp ~/example.com.certbot /etc/nginx/sites-available/example.com
Server
$ sudo nginx -t && sudo systemctl reload nginxnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful
Output hidden (2 lines)
Server
$ for u in http://example.com http://www.example.com https://example.com https://www.example.com; do curl -sS -o /dev/null -w "$u  %{http_code}  %{redirect_url}\n" $u; donehttp://example.com  301  https://example.com/http://www.example.com  301  https://www.example.com/https://example.com  200https://www.example.com  200
Output hidden (4 lines)

certbot’s redirect is back: http goes to https, and www stays www.

What these steps changed on the server

Both runs recorded the server before the first step and after the last (see the Tested on box below). No package was installed, no service was enabled and no port opened or closed: the site already listened on 80 and 443. Only the site’s server block (/etc/nginx/sites-available/example.com) and the certificate files in /etc/letsencrypt/live/example.com/ changed, and seven files were added in /etc/letsencrypt: the second version of the certificate (the one that also names www) and a test-server account from the renewal dry run. The disk holds about 0.4 MB more.

testssl.sh 3.2.5, run against the finished site, gave grade A+ on both releases, with TLS 1.2 and 1.3 on and SSLv2, SSLv3, TLS 1.0 and 1.1 off. Its notes are no DNS CAA record, no security headers and BREACH (flagged because the page is gzip-compressed).

Ubuntu 26.04 vs 24.04: what changed

The steps, the redirects and the renewal behave the same. What differs is in the tools:

WhatUbuntu 26.04Ubuntu 24.04
SystemUbuntu 26.04.1 LTS7.0.0-30-genericUbuntu 24.04.4 LTS6.8.0-138-generic
nginx1.28.3-2ubuntu1.131.24.0-2ubuntu7.20
certbot4.0.0-42.9.0-1
python3-certbot-nginx4.0.0-32.9.0-1
curl8.18.0-1ubuntu2.48.5.0-2ubuntu10.13
VersionsNginx 1.28.3, certbot 4.0.0, curl 8.18.0Nginx 1.24.0, certbot 2.9.0, curl 8.5.0
curl’s certificate error for wwwtarget hostname, webpagetarget host name, web page
Order of the two listen … 443 lines certbot writes443 first[::]:443 first
The four addresses, the one hop, 301 vs 308, renewal, the loopsame textsame text
testssl.sh gradeA+A+ (adds a “no KEMs offered” note)
ProofRun log, 36 checks passedRun log, 36 checks passed