Home / Configs / Servers / nginx redirect www to non-www

nginx redirect www to non-www (or the other way round)

Send www.example.com to example.com (or the reverse) with one permanent redirect.

For nginx 1.18 or newer on Linux, with a main server block for your site already in place.

Search engines treat www.example.com and example.com as two sites unless you pick one. This config sends the other address to your chosen one with a permanent 301 redirect. Keep your main server block as it is and add this one beside it.

Create your config file

Type your own values. The file below updates as you type, and nothing you type leaves your browser.

Enter it without www

/etc/nginx/conf.d/redirect-www.conf
server {
  listen 80;
  server_name www.example.com;
  return 301 https://example.com$request_uri;
}

How this setup works

Diagram: Visitor, then nginx, then Your main site
Visitor (types the other address) → nginx (answers 301) → Your main site (one address only)

Step-by-step setup

  1. Save the config above as /etc/nginx/conf.d/redirect-www.conf.
  2. Make sure your main server block uses the address you want to keep in its server_name.
  3. If you redirect HTTPS too, the certificate must cover both the www and non-www names.
  4. Test the config: sudo nginx -t.
  5. Apply it: sudo systemctl reload nginx.
  6. Check the redirect: curl -I http://www.example.com should show a 301 and a Location line.

What the important lines mean

Common errors and how to fix them

ERR_TOO_MANY_REDIRECTS
Two redirects point at each other. Your main server block must not redirect the address you chose to keep, and the app or CMS must not also redirect it.
Your connection is not private (certificate name mismatch)
The certificate does not list the address being redirected. Issue one that covers both example.com and www.example.com, for example with certbot -d example.com -d www.example.com.
nginx: [warn] conflicting server name
Two server blocks use the same server_name on the same port. Remove or change the duplicate.
nginx -t says "duplicate listen options"
Only one block per port may carry options such as default_server. Remove the extra one.

Frequently asked questions

Should I use www or non-www?
Either is fine for search. Pick one, use it everywhere and redirect the other. Non-www is shorter. www can be easier to move to a CDN later.
Is 301 or 302 right for this?
Use 301. It is permanent, so search engines move to the new address and keep your ranking.
Do I need an SSL certificate for the redirect?
For http:// requests no. For https://www requests yes, because the browser checks the certificate before it sees the redirect.

Written for: nginx 1.24 or newer · Updated 2026-10-11

Free tools that help

Fix a problem with this setup

More server configs

See all 41 config generators