Advertisements

Redirect non-www to www (and vice-versa) via htaccess

This is probably old news for a lot of folks, but it’s handy nonetheless and I often have to look up these .htaccess strings. Note that Apache mod_rewrite is required for any of this to work.

This (and it’s comments) are based on the Drupal default .htaccess file [License as of 9/30/11: GPL], because the Drupal .htaccess file explains it very well. Mind that lines starting with # are comments. Uncomment them to make them take effect.

Also, this should NOT be used with a WordPress install (it will result in a redirect loop). Instead, make the change in Dashboard > Settings > General.

RewriteEngine On
# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} !^www. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

Questions, comments, or feedback? Please leave a comment below. Thank you!

Advertisements

, , ,