Saturday 29 September 2012

Create a generic www redirect app for Webfaction

I've just been struggling with getting my hosted websites to automatically redirect from http://domainname.ext to http://www.domainname.ext .  Now it's working I thought I'd share how it's done.

Note: These instructions apply specifically to websites hosted by the hosting company WebFaction

Uunless told otherwise, Google will treat "www." and "non www." versions of the same website as two separate sites, with implications for page rankings, etc.  So there's a clear need to push one version of the site over the other, and the most foolproof way of doing this is to redirect (using HTTP 301) one version to the other.

There's some debate as to which one you should keep and which you should redirect, but for the purposes of this article, we're going to go from "non www" to "www".

Now Webfaction, a company which I like very much, have some documentation on how to do this, but this particular scenario isn't spelt out, and you can make it more generic than their instructions suggest.

So, in the control panel:

  1. Create a new Static/CGI/PHP-5.x application
  2. Call it "apache_redirects"
  3. Look at the websites page in the control panel and find any sites where you're using both www and non-www domains on a single website
  4. Remove the non-www domain from each website
  5. Create a new website, call it "redirects", add ALL the non-www domains to it, and point it to the apache_redirects application
  6. Hit save

Now, SSH into the server, and:

  1. cd /home/username/webapps/apache_redirects
  2. vi .htaccess (I'm assuming you know how to insert and edit text in vi, if not pick another editor)
  3. add the following lines, and save the file
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L,NC]

Job done!  There's no need to create multiple versions and hard code the domain details in the above two lines, because this version works fine.
                                                                                            




No comments:

Post a Comment