Skip to main content

Web servers and networking · Beginner · 11 min

Redirect HTTP to HTTPS and www to the bare domain in Nginx

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · Nginx 1.30.8 stable (nginx.org repo)

You will send every plain-HTTP and www request on Nginx 1.30 to https://example.com in a single 301 hop, with the path and query string kept, and have a script that checks all four combinations.

On this page

A site with HTTPS and a www name can be reached at four addresses: http://example.com, http://www.example.com, https://example.com and https://www.example.com. Only one of them should serve pages. The other three should send the visitor there, straight away, with the path and query string intact, so links, bookmarks and search results all land on the same canonical address.

The setup Certbot leaves behind usually gets this half right. It redirects HTTP to HTTPS, but keeps the host name, so http://www.example.com goes to https://www.example.com, which serves a second copy of the site. Adding a www redirect on top of that often creates a chain: HTTP www to HTTPS www, then HTTPS www to HTTPS bare. Every extra hop is another round trip, and a hop to a different host name means a new TLS handshake as well.

In this tutorial you will make https://example.com the canonical address. Replace example.com with your own domain throughout. If you prefer www as the canonical name, swap the two names in every server block; the structure is the same. You will write a small script that checks all four addresses, confirm the certificate covers both names, add a catch-all HTTP server, send www to the bare domain in one hop, and add HSTS last.

Step 1 · Record how the site answers today

Before you change anything, find out what each of the four addresses does now. The script below requests each one with a query string attached, and for each prints the first status code, where the request finally ends up, and how many redirects it took. It marks a line ok only when the request ends at https://example.com with the query string intact, after at most one redirect.

Create it in a throwaway folder:

Bash
mkdir -p ~/redirect-demo
cat > ~/redirect-demo/check-redirects.sh <<'SH'
#!/usr/bin/env bash
# Usage: check-redirects.sh example.com
# Requests the four scheme and host combinations with a query string and
# prints the first status, the final address and the number of redirects.
set -u
domain="${1:?give the bare domain, for example: example.com}"
path='/?ref=newsletter&page=2'
want="https://$domain$path"
for url in "http://$domain$path" "http://www.$domain$path" "https://$domain$path" "https://www.$domain$path"; do
  first=$(curl -sI -o /dev/null -w '%{http_code}' "$url")
  read -r hops code final < <(curl -sIL -o /dev/null -w '%{num_redirects} %{http_code} %{url_effective}\n' "$url")
  if [ "$final" = "$want" ] && [ "$code" = 200 ] && [ "$hops" -le 1 ]; then verdict=ok; else verdict=FIX; fi
  printf '%-4s %-42s first=%s final=%s %s redirects=%s\n' "$verdict" "$url" "$first" "$code" "$final" "$hops"
done
SH
chmod +x ~/redirect-demo/check-redirects.sh
~/redirect-demo/check-redirects.sh example.com

curl -I sends HEAD requests, so nothing is downloaded. -L follows redirects, and %{num_redirects} counts them. With the setup Certbot usually leaves, the output looks something like this:

Text
ok   http://example.com/?ref=newsletter&page=2  first=301 final=200 https://example.com/?ref=newsletter&page=2 redirects=1
FIX  http://www.example.com/?ref=newsletter&page=2 first=301 final=200 https://www.example.com/?ref=newsletter&page=2 redirects=1
ok   https://example.com/?ref=newsletter&page=2 first=200 final=200 https://example.com/?ref=newsletter&page=2 redirects=0
FIX  https://www.example.com/?ref=newsletter&page=2 first=200 final=200 https://www.example.com/?ref=newsletter&page=2 redirects=0

Both www lines end on https://www.example.com, which serves the same pages as the bare domain. That is the duplicate you are about to remove.

Find the file that holds your site's server blocks, then keep a copy so you can go back:

Bash
sudo grep -rln 'server_name.*example.com' /etc/nginx/conf.d/
cp /etc/nginx/conf.d/example.com.conf ~/redirect-demo/example.com.conf.before

This tutorial assumes the file is /etc/nginx/conf.d/example.com.conf. Use whichever path the grep prints.

Check it worked

The script printed four lines, you can see which ones say FIX, and ls ~/redirect-demo lists check-redirects.sh and example.com.conf.before.

Step 2 · Confirm the certificate covers both names

A redirect from https://www.example.com can only happen after the TLS handshake succeeds. If the certificate does not name www.example.com, the browser shows a certificate warning and never sees the redirect. So the certificate must list both names, even though www will never serve a page.

Bash
sudo openssl x509 -in /etc/letsencrypt/live/example.com/fullchain.pem -noout -subject -ext subjectAltName

You want both names under Subject Alternative Name:

Text
subject=CN=example.com
X509v3 Subject Alternative Name:
    DNS:example.com, DNS:www.example.com

If DNS:www.example.com is missing, add it to the existing certificate. --cert-name keeps the same certificate and file paths, and certonly stops Certbot from editing your Nginx files, which you are about to rewrite by hand. The www DNS record must already point at this server:

Bash
sudo certbot certonly --nginx --cert-name example.com -d example.com,www.example.com
sudo systemctl reload nginx

Certbot asks you to confirm that you are changing the certificate's names. Then run the openssl command again.

Check it worked

The openssl output lists both DNS:example.com and DNS:www.example.com.

Step 3 · Pick the status code and add a catch-all HTTP server

Three status codes matter for this job:

  • 301 Moved Permanently tells clients and search engines that the new address replaces the old one. Browsers cache it, often for a long time. Browsers and many other clients turn a POST into a GET when they follow it.
  • 308 Permanent Redirect means the same, but the client must repeat the request with the same method and body. Use it on hostnames that receive POST requests over plain HTTP, such as an API that old clients still call on port 80.
  • 302 Found is temporary. Clients keep using the old address and do not cache the redirect by default.

For a website, use 301. Because browsers cache it, a mistake can stick around in your own browser after you fix it. While you experiment, you can write 302 and change it to 301 once the checks in this tutorial pass.

Instead of one HTTP block per site, you can have a single server that answers every name on port 80 and sends it to HTTPS. In Nginx, default_server on a listen line makes that block answer any request whose Host header matches no other server_name on that port. server_name _; is a convention: _ is a name no request will ever use, so the block is only reached as the default.

There can be only one default_server per address and port. Before you add yours, check whether another block already claims it:

Bash
sudo grep -rn 'default_server' /etc/nginx/ || echo "no default_server set yet"

If a listen 80 default_server line appears in another file, remove default_server from that line first, or nginx -t fails with a duplicate default server error. A block that is the default for port 443 does not conflict.

If you followed /tutorials/host-multiple-sites-with-nginx-server-blocks, the match is /etc/nginx/conf.d/00-default.conf, which returns 444 to unknown names on port 80. This redirect replaces that catch-all, so delete the file with sudo rm /etc/nginx/conf.d/00-default.conf, or remove default_server from both of its listen lines (80 and [::]:80).

Create the catch-all in its own file:

Bash
sudo tee /etc/nginx/conf.d/00-redirect-to-https.conf > /dev/null <<'NGINX'
# Every request on port 80 that no other server block claims goes to HTTPS,
# on the same host name, with the full original path and query string.
server {
    listen 80 default_server;
    server_name _;
    return 301 https://$host$request_uri;
}
NGINX

Two variables do the work. $host is the host name the client asked for. $request_uri is the original path with its query string, exactly as the client sent it. Do not use $uri here: it is the decoded, normalised path without the query string, so ?ref=newsletter&page=2 would be lost.

If your server blocks also listen on IPv6 (listen [::]:80;), add listen [::]:80 default_server; under the first listen line.

Now the old port 80 block in your site file is no longer needed: the catch-all handles example.com on port 80 the same way. Open the site file:

Bash
sudo nano /etc/nginx/conf.d/example.com.conf

Delete the whole server { ... } block that has listen 80;. If Certbot wrote it, it may contain if ($host = example.com) lines and return 404;, all marked # managed by Certbot. Keep the HTTPS block as it is, including any include /etc/letsencrypt/options-ssl-nginx.conf; and ssl_dhparam lines. The file now holds only the HTTPS block:

Nginx
server {
    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;

    root /var/www/example.com;
    index index.html;
}

Test, then reload:

Bash
sudo nginx -t && sudo systemctl reload nginx

Check it worked

Ask for the bare domain over HTTP, then for a name the server has no block for:

Bash
curl -sI 'http://example.com/?ref=newsletter&page=2' | grep -iE '^(HTTP|location)'
curl -sI -H 'Host: other.example' http://127.0.0.1/ | grep -iE '^(HTTP|location)'

The first prints HTTP/1.1 301 Moved Permanently and Location: https://example.com/?ref=newsletter&page=2, with the query string kept. The second shows the catch-all at work: Location: https://other.example/.

Step 4 · Send www to the bare domain in one hop

Right now http://www.example.com goes to https://www.example.com, and that still serves the site. Two new server blocks fix it, one per port, and both point straight at the final address:

  • On port 80, a block for www.example.com returns https://example.com$request_uri. Because it names www exactly, Nginx picks it over the catch-all, so HTTP www skips the HTTPS www stop and arrives in one hop.
  • On port 443, a block for www.example.com does the TLS handshake with your certificate, then returns the same redirect.

The main HTTPS block then names only example.com.

Open the site file again:

Bash
sudo nano /etc/nginx/conf.d/example.com.conf

Make it match this. Note the hard-coded https://example.com in the www blocks, rather than $host, which would keep www. If your HTTPS block has http2 on; or Certbot's include and ssl_dhparam lines, copy them into the new www HTTPS block as well.

Nginx
# www over plain HTTP: straight to the final address, skipping https://www
server {
    listen 80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

# www over HTTPS: finish the handshake, then send the visitor on
server {
    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;

    return 301 https://example.com$request_uri;
}

# The canonical site
server {
    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;

    root /var/www/example.com;
    index index.html;
}
Bash
sudo nginx -t && sudo systemctl reload nginx

Check it worked

Bash
curl -sI 'https://www.example.com/blog/?page=2' | grep -iE '^(HTTP|location)'
curl -sI 'http://www.example.com/blog/?page=2' | grep -iE '^(HTTP|location)'

Both print a 301 status and location: https://example.com/blog/?page=2. The HTTPS request shows the status as HTTP/1.1 301 Moved Permanently, or HTTP/2 301 if your block has http2 on;.

Step 5 · Check every combination reaches its final address in one hop

Run the script from the first step again:

Bash
~/redirect-demo/check-redirects.sh example.com

All four lines now start with ok. The three redirecting addresses show first=301 and redirects=1, and the canonical one shows first=200 and redirects=0. Every line ends on https://example.com/?ref=newsletter&page=2.

One hop is worth the care. On a high-latency mobile connection, common for visitors on prepaid data in much of Africa and elsewhere, each redirect to a new host name costs a DNS lookup, a TCP connection and a TLS handshake before the first byte of the page arrives. Removing a hop can save a noticeable fraction of a second on every first visit.

Run the script from your own computer too, since it then goes through real DNS and any firewall or load balancer in front of the server. It works on macOS and Linux.

If Certbot renews this certificate with its Nginx plugin, check that renewal still works with the new layout. This contacts the Let's Encrypt staging service and changes nothing:

Bash
sudo certbot renew --dry-run

It ends with a line saying the simulated renewal succeeded. If it fails on the www name, look at the error before the next real renewal, which Certbot attempts when about a third of the certificate's lifetime is left.

Finally, open http://www.example.com/?ref=test in a private browser window. The address bar shows https://example.com/?ref=test.

Check it worked

The script prints four ok lines from the server and from your computer, certbot renew --dry-run succeeds, and the browser lands on the bare HTTPS address with the query string intact.

Step 6 · Add HSTS once the redirects are right

HSTS (the Strict-Transport-Security header) tells browsers to use HTTPS for your host name and never try plain HTTP again. Add it last, for three reasons. Browsers ignore it on plain-HTTP responses, so it only works on HTTPS blocks. It is cached for its full max-age, so a mistake sticks. And it should go on each host name that serves HTTPS, including the www redirect block, so returning www visitors skip the HTTP hop too.

Start with five minutes. Add the same line to both listen 443 ssl blocks in the site file:

Bash
sudo nano /etc/nginx/conf.d/example.com.conf
Nginx
    add_header Strict-Transport-Security "max-age=300" always;

Put it under the ssl_certificate_key line in each HTTPS block. always makes Nginx send it with every response, including errors. If a location block inside the canonical site has an add_header of its own, it stops inheriting this one: the security headers tutorial explains that trap and how to keep all headers in one included file.

Bash
sudo nginx -t && sudo systemctl reload nginx

Once it has run without problems for a few days, raise max-age in steps, as described in the security headers tutorial, and only then consider includeSubDomains.

Check it worked

Bash
curl -sI https://example.com/ | grep -i '^strict-transport-security'
curl -sI https://www.example.com/ | grep -i '^strict-transport-security'
curl -sI http://example.com/ | grep -i '^strict-transport-security' || echo "no HSTS over plain HTTP, as expected"
~/redirect-demo/check-redirects.sh example.com

The first two print strict-transport-security: max-age=300, the third prints no HSTS over plain HTTP, as expected, and the script still prints four ok lines.

To undo the whole change, copy ~/redirect-demo/example.com.conf.before back over the site file, delete /etc/nginx/conf.d/00-redirect-to-https.conf, then test and reload. Browsers that cached the 301 or the HSTS header keep using HTTPS on the bare domain until those expire, which does no harm.

Next steps

  • Roll out the rest of the security headers, and raise HSTS safely: /tutorials/add-security-headers-in-nginx.
  • Add a second site to the same server, skipping that tutorial's 00-default.conf step because the catch-all here already covers its HTTP traffic: /tutorials/host-multiple-sites-with-nginx-server-blocks.
  • Revisit how the certificate is issued and renewed: /tutorials/free-https-with-lets-encrypt-and-nginx.
  • Follow a redirect hop by hop with curl's timers: /tutorials/debug-a-slow-or-failing-website-with-curl.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.