Monday, March 23, 2009

Rewriting www to non-www with Apache2

... or how to make mod_rewrite your friend.

Like many other hipster sites in the whole new series of tubes we call web2.0, I wanted to have my site reside at http://helpleaf.com rather than the old, redundant, crappy http://www.healpleaf.com. So I tried to set that up. After all, how hard could setting up a non-www RewriteRule be?

Well, as I learned, not hard if you know what you’re doing. Since I don’t, it was friggin’ hard. But, after wrestling with this for a couple of hours I enlisted the help of my friend Brett who showed me the easy way.

Here’s what we did…

My domain registrar is GoDaddy, but I transferred DNS control to SliceHost where my site resides (and whose DNS control I like a LOT better).

Then I set up my DNS records. Because DNS admin tools are really different from host to host you'll have ot figure out the exact ways to handle doing the following DNS stuff.

My domain is helpleaf.com so I created an A record pointing from helpleaf.com. to the IP address of my server.

At this point I had a choice, either:

1. create another A record for www.helpleaf.com pointing to the IP of my server

or

2. create a CNAME record for www pointing to helpleaf.com

I went with the latter because I am less likely to screw it up if I change IPs on the server since there’s only the one A record to update. (Note that this causes more heat on the DNS server, but since my traffic is low… meh.)

Now the trickiness (this is where Brett comes in handy)…

change to the apache2/sites-enabled directory

cd /etc/apache2/sites-enabled

and create a new file:

sudo nano www.helpleaf.com

Here is the full content of that file:

<virtualhost>
ServerName www.helpleaf.com
ServerAlias www.helpleaf.com

DocumentRoot /home/bruce/helpleaf/public

RewriteEngine On

# rewrite anything incoming to helpleaf.com
RewriteRule ^(.*)$ http://helpleaf.com$1 [R=301,L]

# Custom log file locations
# so I can see the www traffic sources
ErrorLog /home/bruce/helpleaf/log/www.error.log
CustomLog /home/bruce/helpleaf/log/www.access.log combined

</virtualhost>

Just reload the apache2 config

sudo service apache2 reload

Let’s try that out. Open a browser and go to http://www.helpleaf.com.

Badda BING!

You should be redirected to http://helpleaf.com.

That’s it.