How to Redirect www to non-www

Send every www.yourdomain.com request to yourdomain.com with a 301 redirect on Vercel, Netlify, Cloudflare, nginx or Apache, then confirm it with curl.

Your site answers at both www.yourdomain.com and yourdomain.com. Search engines treat those as two sites, so pick one and redirect the other. These steps send www to the bare domain; swap the hostnames to go the other way.

Give both hostnames DNS and SSL

A redirect only runs once the browser reaches a server, so www.yourdomain.com needs its own DNS record (an A record, or a CNAME to the host) and a certificate that covers it. Vercel, Netlify and Cloudflare issue that certificate on their own once the record points at them. On a self-managed server, include both names when requesting the certificate.

Use the host's redirect setting

  • Vercel: Settings, Domains. Add both domains, then edit the www entry and set it to redirect to yourdomain.com with a 308 status.
  • Netlify: Site configuration, Domain management. Set yourdomain.com as the primary domain. Netlify redirects the other one on its own.
  • Cloudflare: Rules, Redirect Rules, Create rule. Match Hostname equals www.yourdomain.com, choose Dynamic, and use this expression with status 301:
concat("https://yourdomain.com", http.request.uri.path)

The www DNS record must be proxied (orange cloud) for the rule to run.

Add the redirect on nginx

server {
    listen 80;
    listen 443 ssl;
    server_name www.yourdomain.com;
    # ssl_certificate and ssl_certificate_key lines go here
    return 301 https://yourdomain.com$request_uri;
}

Then run sudo nginx -t && sudo systemctl reload nginx.

Add the redirect on Apache

Put this at the top of the .htaccess file in the web root. It needs mod_rewrite enabled and AllowOverride All for the directory.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ https://yourdomain.com/$1 [R=301,L]

Test with curl

curl -I https://www.yourdomain.com/some-page

Expect a 301 or 308 status and a location: header of https://yourdomain.com/some-page. The path must survive the redirect. Repeat with http://www.yourdomain.com to confirm the plain HTTP version also lands on the bare HTTPS domain, even if it takes two hops.

Match the canonical tags. Every page's <link rel="canonical"> should use the version you kept, and so should the sitemap and any internal links. A redirect to yourdomain.com paired with canonical tags pointing at www sends search engines mixed signals.

More Websites how-tos