Bandit Design » Our Design Our Portfolio Contact Us
Tutorials TumbleLog Our Thoughts
Quite often at Bandit Design while we're working on your project, we'll stumble upon interesting or humourous things -- so we thought why not share them with the world!
RSS iPhone Random Archive « Home

Bandit Design

This is a TumbleLog authored at the desks of Bandit Design. We're a small web and graphic design studio based in Wellington, New Zealand.

Visit Bandit Design ยป

2 years ago

Redirecting all non www. requests via htaccess

For our cycle community system we have a bunch of domains all using the same codebase, running via Apache Virtual Hosts.

In order to maximise Google juice, we redirect all requests that don’t start with “www.” to the associated “www” subdomain. For example http://icyclenow.co.nz will be redirected to http://www.icyclenow.co.nz.

In order to do this simply we use htaccess and mod_rewrite and reference RewriteCond variables like so:

# Redirect all requests not starting with "www." to their www subdomain
RewriteCond %{HTTP_HOST} !localhost [NC]
RewriteCond %{HTTP_HOST} !www. [NC]
RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,NC,L]

The first line just makes sure we’re not on a local dev environment.
The second line checks for “www.” within the HTTP_HOST (everything after http:// and before the first /).
The third line grabs our HTTP_HOST into a capture group — ^(.*)$ matches *anything*.

The forth line is where the magic happens:
We replace the entire request (^(.*)$) with http://www. and the two capture groups.
We use %1 which references the capture group from line 3, and $1 which references the capture group from this line.
Finally we end with [R=301,NC,L]. R=301 simply means do a full page redirect using a 301 header (permanently moved - this is what maximises our Google juice), NC means no case (meaning it will match UPPER or lower case) and L means stop and redirect immediately.

Hopefully this helps someone! More useful tips here.

- James

Loading...