Orange is my favorite color

The title is a long way of saying I have and I also have, plural, in case people mistype the name. If someone hits my site as, I want to automatically correct it to be to maintain my branding. This is pretty straightforward to fix with your <VirtualHost> and mod_rewrite:

RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*)$1 [L,R=301]

But what if you allow customized, arbitrary subdomains other than “www”, like “myclub” and you want to support users who type in but automatically redirect them to This is less clear and it took a good number of tries and a little brainstorming on the BACFUG list to get it working:

ServerAlias *
ServerAlias *
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-]+) [NC]
RewriteRule (.*)$1 [L]

This will redirect to Note the different backreferences %2 and $1 reflecting the difference between the RewriteCond and the RewriteRule. It’s important to note that you can only use the RewriteCond backreferences for the last RewriteCond. If you chain several of them together, only the last one will be available in the final RewriteRule.

1 Comment

  1. This is Tyler Fitch » Blog Archive » links for 2008-12-17 said:

    on December 17, 2008 at 10:30 pm

    [...] Orange is my favorite color » Blog Archive » Using Apache and mod_rewrite to correct alternative h… (tags: mod_rewrite apache subdomains) Posted in | [...]

{ RSS feed for comments on this post}