Forcing the www in front of the url with mod_rewrite

Problem: My website could be accessed with http://www.plcdev.com or http://plcdev.com. While it doesn't seem like much of a problem it caused Google Adsense to go wacky since it doesn't have http://plcdev.com indexed. It also creates problems with search engines not realizing that these two links are the same and therefore diminishing the page rank.

Solution: You must have Apache's mod_rewrite enabled on your web host.  Create an .htaccess file and add the following

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

This example works for multiple domains with either a .com or .org ending. 

For Drupal users this works great in the existing htaccess file in the Various rewrite rules section before any of the other rules.


( categories: )