Orange is my favorite color

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

ServerAlias domains.com
ServerAlias www.domains.com
RewriteCond %{HTTP_HOST} !^www\.domain\.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://www.domain.com/$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 myclub.domainS.com but automatically redirect them to myclub.domain.com? 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 *.domain.com
ServerAlias *.domains.com
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-]+).domains.com [NC]
RewriteRule (.*) http://%2.domain.com$1 [L]

This will redirect myclub.domainS.com/foo/bar to myclub.domain.com/foo/bar. 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 del.icio.us | [...]

{ RSS feed for comments on this post}