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 rather than the old, redundant, crappy 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 so I created an A record pointing from to the IP address of my server.

At this point I had a choice, either:

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


2. create a CNAME record for www pointing to

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

Here is the full content of that file:


DocumentRoot /home/bruce/helpleaf/public

RewriteEngine On

# rewrite anything incoming to
RewriteRule ^(.*)$$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


Just reload the apache2 config

sudo service apache2 reload

Let’s try that out. Open a browser and go to

Badda BING!

You should be redirected to

That’s it.