.htaccess rules below still work on Apache servers, but modern setups (NGINX, Caddy, Apache 2.4 with virtual hosts) handle redirects differently. The rules also use http:// — update them to https:// for any SSL-enabled site.
Every domain can be accessed through two different URLs. Take example.com — it’s reachable as both example.com and www.example.com. The same applies to subdomains. From a user’s point of view this doesn’t matter much, but from an SEO standpoint it’s a problem. Having the same content available on two different URLs can be flagged as duplicate content and hurt your search rankings.
To avoid this, you need to pick one canonical version and redirect the other to it permanently.
You have two options: redirect all www URLs to their non-www equivalent, or redirect non-www to www. Either works, but redirecting to non-www is generally recommended since it results in shorter, cleaner URLs.
Setting up the redirect
Locate your .htaccess file in your site’s root directory. If it doesn’t exist, create one. Then add the relevant block below.
To redirect www to non-www (recommended):
# Rewrite "www.example.com -> example.com".
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
</IfModule>
To redirect non-www to www:
# Rewrite "example.com -> www.example.com".
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^www..+$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>
Save the file and you’re done. The R=301 flag tells search engines this is a permanent redirect.