Generic Apache Redirect to Add www to Domain Name

It's common to want to add "www" to a domain name, so that users typing in the "non-www" domain name, will get to the right site. It's important to implement this with a 301 redirect so that search engines recognize that there is only one true and real site. The traditional way to do this is:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^euphline.com$
RewriteRule (.*) http://www.euphline.com/$1 [R=301,L]

There are times, though, such as when one is running Drupal with Domain Access, that one wants a generic rewrite. In other words, we want to say, "For any domain where www is not included, add it." This is not quite as freely documented, but it's reasonably intuitive:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.*
RewriteRule (.*) http://www.%{HTTP_HOST}$1 [R=301,L]

Note that there is no / after the %{HTTP_HOST} in the RewriteRule. Including a slash there will result in a double slash.

Tags: