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 to, you’ll have to use an intermediary processor like PHP.

[code lang=”PHP”]

Setting this code as the index.php for 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 as its own VirtualHost with a ServerAlias of * In another VirtualHost, set the ServerName as * with the above index.php in its DocumentRoot won’t match the first, but will match the * (catch-all) VirtualHost, run the index.php, then redirect to the first VirtualHost:

<VirtualHost *:80>
ServerAlias *
DocumentRoot /var/www/

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

Leave a Reply