One of the coolest features about Drupal is the ability to run heaps of sites from the same codebase. However, if you’re a total wacko when it comes to SEO and want to do absolutely everything to help get your site well indexed by Google, it can be difficult to figure out how to get Drupal to manage non-www to www redirects effectively. Because Drupal runs from one codebase, there is just one .htaccess file in the directory holding the main Drupal code. You could just copy the .htaccess file and place it into your /sites/sitename folder, but if you have hundreds of sites to manage, this could be a pain in the ass. So, what do you do?
After plenty of Googling about the subject, I finally tracked down some neat code to help you. Here’s the link to a ‘how to’ on the subject.
In my case, I wished to redirect all non-www traffic to the www version of each site, so I used:
# non empty HTTP_HOST in the request
RewriteCond %{HTTP_HOST} !^$ [NC]
# does not start with 'www'
RewriteCond %{HTTP_HOST} !^www\. [NC]
# saves the value of HTTP_HOST in %1
RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
# redirects using the saved URI (in RewriteRule) and saved hostname (in the last RewriteCond)
RewriteRule ^(.*)$ "http://www.%1/$1" [L,R=301]
# that's it !
Obviously, don’t forget to save a backup of your .htaccess file when upgrading Drupal to the newest version!
{ 3 comments… read them below or add one }
Hi, this is terrific… do you have any idea how I could reverse it, so that the script redirects from www to non-www?
Thanks so much for making this available.
Hey David,
Thanks for the comment!
Basically you’d just reverse the rule – i.e. in the first part remove the ‘www’ bit, and in the latter remove the ‘www’. Trial and error should get you up and running in no time, you may have to refresh Apache though when you’re done.
This works except for it changes my domain from this:
http://domain.com/terms/title
to this:
http://domain.com/index.php?q=terms/title
which is even worse, how do I remove the index.php?q=