Apache: Use .htaccess to redirect non-www to www

Posted by Andrew McCombe on Sat Aug 25, 2018

Sometimes your website will be set up to serve your site on both www.domain.com and also domain.com. Search engines will see this as two separate sites (unless you have a rel="canonical" tag) and this may have a negative effect on your SEO rankings.

The best way to avoid this is to make sure you serve your site from one canonical domain. You can use Apache’s .htaccess to permanently redirect any non-www requests:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [L,R=301]