Operating System CentOS

How to Redirect Non-www to www (or www to Non-www) in Nginx

Pick one canonical host name and make Nginx redirect the other to it: per-domain server blocks, a regex catch-all for many domains, and how to test with curl.

A site that answers on both example.com and www.example.com should pick one of the two as its canonical name and redirect the other to it. This guide shows how to do that in Nginx in either direction, for one domain or for every domain on the server, and how to check the result. The configuration is the same on Ubuntu 26.04 LTS and 24.04 LTS, Debian 13 and 12, and AlmaLinux 9, Rocky Linux 9 and CentOS Stream 9; only the location of the configuration files differs.

Requirements

  • A server with Nginx installed and a user with sudo rights.
  • DNS records for both names (example.com and www.example.com) pointing to the server, for example to 203.0.113.10. A name that does not resolve to the server can never be redirected by it.
  • If the site uses HTTPS, a certificate that is valid for both names. The browser checks the certificate before it reads the redirect, so a certificate that covers only the canonical name produces a warning on the other one.

On Ubuntu and Debian the distribution packages keep site files in /etc/nginx/sites-available/, linked into /etc/nginx/sites-enabled/. On the RHEL family, and with the packages from nginx.org, site files are /etc/nginx/conf.d/*.conf. Put the server blocks below in the file that already holds your site.

Redirect non-www to www for one domain

Give the name you want to get rid of its own server block that does nothing except redirect. This is the method the Nginx documentation recommends; testing the host name with if inside a shared block works but is described there as the wrong way to do it.

server {
    listen 80;
    listen [::]:80;
    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;

    return 301 $scheme://www.example.com$request_uri;
}

server {
    listen 80;
    listen [::]:80;
    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;

    root /var/www/example.com;
    # the rest of the site configuration
}

$scheme keeps the protocol the visitor used and $request_uri keeps the path and query string, so http://example.com/blog?page=2 becomes http://www.example.com/blog?page=2. If the site has no HTTPS yet, remove the two listen 443 lines and the two ssl_certificate lines from both blocks. Adjust the certificate paths to wherever your certificate is stored.

Redirect www to non-www for one domain

For the opposite direction, swap the names: the redirecting block answers for www.example.com and the site block for example.com.

server {
    listen 80;
    listen [::]:80;
    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;

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

Redirect every domain on the server at once

When a server hosts many domains, one block with a regular expression name can handle all of them. A server_name that starts with ~ is a regular expression, and a named capture becomes a variable you can use in the redirect.

To strip www. from any host name:

server {
    listen 80;
    listen [::]:80;
    server_name ~^www\.(?<domain>.+)$;
    return 301 $scheme://$domain$request_uri;
}

To add www. to any host name that does not have it:

server {
    listen 80;
    listen [::]:80;
    server_name ~^(?!www\.)(?<domain>.+)$;
    return 301 $scheme://www.$domain$request_uri;
}

Three things to know before you use these:

  • Nginx tries exact names first and regular expressions last, so a site block with an exact server_name always wins. The second pattern would turn blog.example.com into www.blog.example.com unless blog.example.com has its own block.
  • Dots in the pattern must be escaped (\.), and the ^ and $ anchors should be present. A pattern that contains { or } has to be wrapped in double quotes.
  • These examples listen on port 80 only. A catch-all on port 443 needs a certificate that is valid for every name it may receive, which is rarely the case; for HTTPS sites use the per-domain blocks above. Regular expression names are also the slowest kind to match, so prefer exact names when you have only a few domains.

Choose 301 or 302

301 is a permanent redirect: search engines move the indexed address to the new name and browsers cache the answer, sometimes for a long time. 302 is temporary and is not cached in the same way. While you are still testing, use return 302 …, and change it to 301 once the behaviour is right. A mistake published as a 301 can stay in visitors' browsers after you fix the server.

Apply and test

Check the syntax, then reload Nginx without dropping connections:

sudo nginx -t
sudo systemctl reload nginx

Test with curl rather than a browser, because curl does not cache redirects:

curl -I "http://example.com/blog?page=2"

The response should start with the status line and contain the new address:

HTTP/1.1 301 Moved Permanently
Location: http://www.example.com/blog?page=2

Repeat the test with https://, and request the canonical name as well to confirm that it answers with 200 and not with another redirect.

Troubleshooting

  • Redirect loop. Something else redirects in the opposite direction: an application setting for the site address, or a CDN or proxy in front of the server. Make all of them agree on the same canonical name.
  • The redirect does not happen. Another block is answering. sudo nginx -T | grep -n server_name lists every name Nginx knows; make sure the redirected name appears only in the redirecting block.
  • Certificate warning before the redirect. The certificate does not include the redirected name. Reissue it with both names.

Frequently asked questions

Is www or non-www better?

Neither ranks better. The bare domain is shorter. The www name is more flexible in DNS, because it can be a CNAME to a CDN or load balancer while a bare domain normally cannot, and cookies set for it are not sent to every other subdomain. What matters is choosing one and redirecting the other consistently.

Does the redirect keep the path and query string?

Yes, as long as the target ends in $request_uri, which holds the original path including the query string. Leaving it out sends every visitor to the home page.

Why does Nginx say "conflicting server name"?

The same name is listed in two server blocks on the same port, usually because the old site block still contains both names. Remove the redirected name from the site block and reload.

Can the same block also force HTTPS?

Yes. Replace $scheme with https in the return line and the visitor goes to the canonical name and to HTTPS in one step instead of two.

Share story:

Continue reading other guides on How VPS.