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

August 25th, 2018

Warning: This post is 5 years old. Some of this information may be out of date.

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]