redirect aliased hosts to a single canonical host with apache

We have a new Apache 2.2/mongrel server set up, and wanted people who type in host.com to be redirected to www.host.com, instead of merely aliasing all the same content and confusing Google. This is an obvious thing, but I still had trouble finding a straightforward how-to, so here it is.

old, bad way

All of this takes place in your httpd.conf, or your vhost.conf, or whatever file refers to your host in question in whatever of the infinite Apache configuration possibilities you have managed to implement.

Here’s what you probably had before:

<VirtualHost *:80>
  ServerName www.site.com
  ServerAlias site.com blog.site.com

  <Proxy balancer://site_com_cluster>
    BalancerMember http://127.0.0.1:3050
# etc...

new, awesome way

If you want a specific redirect type (303, permanent, etc.), you can put it after the Redirect keyword. But this way works fine, and the word on the street is that Google treats every type as a 301 anyway, so it doesn’t really matter what you put.

Here’s what you should have:

<VirtualHost *:80>
  ServerName site.com
  ServerAlias blog.site.com
  Redirect / http://www.site.com/
</VirtualHost>

<VirtualHost *:80>
  ServerName www.site.com

  <Proxy balancer://site_com_cluster>
    BalancerMember http://127.0.0.1:3050
# etc...

the end

Shed a tear for lighttpd; we were driven away by a bizarre rendering bug in Camping/fastcgi (extra linebreak before every output body, even with x-sendfile). Unfortunately Apache/mongrel does not seem super-stable at this point.

Deployment… sucks.