Adding or Removing www. with RewriteEngine

Most websites have two hosts: the www host (ie. www.google.com) and the non-www host (ie. google.com). Since search engines don’t like duplicate content, it is good practice to either make sure your site always has the www, or always remove it. ┬áSince you don’t have any control over how the Internet user types in your site, here’s a simple way of either adding or removing the www.

In order for this to work, your site needs to be running on an Apache server, and mod_rewrite should be enabled.┬áMake sure this is at the top of the .htaccess file: (if you don’t have an .htaccess file, create one in the web directory and put this at the top)

RewriteEngine on
Options Indexes FollowSymLinks

Insert this snipped to add the www to all requests:

# add www
RewriteCond %{SERVER_PORT} 443
RewriteCond %{HTTP_HOST} !^www\\. [NC]
RewriteCond %{HTTP_HOST} !^$ [NC]
RewriteRule ^/?(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L,NE]

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

Or insert this snipped to remove the www from all requests:

# remove www
RewriteCond %{SERVER_PORT} 443
RewriteCond %{HTTP_HOST} ^www\\. [NC]
RewriteCond %{HTTP_HOST} !^$ [NC]
RewriteRule ^/?(.*)$ https://%{HTTP_HOST}/$1 [R=301,L,NE]

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

Resources:
Apache’s mod_rewrite Documentation
Apache’s URL Rewriting Guide

Leave a Reply

Your email address will not be published. Required fields are marked *