Enabling Drupal 7 'www' Redirection on a Local Host

This article was published by DrupalEasy as a Quicktip, .

Drupal 7's HTTP access file, .htaccess, contains some URL rewriting code for redirecting all site visitors to the domain name starting with "www.", in case they try to go to the domain name without the prefix. For instance, you might want all visitors to go to www.example.com, and never example.com, for SEO purposes.

This is achieved by uncommenting the code on lines 81-82:

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This works fine when used on a remote server, but not on a local server that is not set up to handle the prefix. For instance, if you have a local installation of Drupal at http://localhost/my_site/, then the rewrite code will change that into an invalid URL: http://www.localhost/my_site/

This problem can be fixed by adding the following line above the RewriteRule:

RewriteCond %{HTTP_HOST} !^localhost$ [NC]

Or, more simply, the existing RewriteCond line can be modified:

RewriteCond %{HTTP_HOST} !^(www\.|localhost$) [NC]
Copyright © 2012 Michael J. Ross. All rights reserved.
bad bots block