Rewriting URLs based on domain name

While Apache’s mod_rewrite is fairly powerful, it does have some limitations (mostly to not break the HTTP spec). While you can specify any number of esoteric conditions, it’s not possible to rewrite anything but the URI. If you want to redirect sillydomaintwo.com to two.sillydomain.com/blog, you’ll have to use an intermediary processor like PHP.

[code lang=”PHP”]
[/code]

Setting this code as the index.php for sillydomaintwo.com will suffice, as it will perform a 301 redirect to the target location.

In Apache, the simplest way to support this sort of configuration is to have the master sillydomain.com as its own VirtualHost with a ServerAlias of *.sillydomain.com. In another VirtualHost, set the ServerName as * with the above index.php in its DocumentRoot sillydomaintwo.com won’t match the first, but will match the * (catch-all) VirtualHost, run the index.php, then redirect to the first VirtualHost:

<VirtualHost *:80>
ServerName sillydomain.com
ServerAlias *.sillydomain.com
DocumentRoot /var/www/sillydomain.com
</VirtualHost>

<VirtualHost *:80>
ServerName *
DocumentRoot /var/www/sillydomain-redirect
#in this directory is the index.php with the redirection as described above
</VirtualHost>

Leave a Reply