The Apache module mod_rewrite is very much en vogue in this web2.0-obsessed world we live in. It’s a powerful tool for URL manipulation, and has many applications that are of interest to the LAMP developer.

I’m currently building a web app that requires wildcard subdomains. So, if the domain name is test.com, the following would all point to the homepage:

http://www.test.com
http://this.is.a.test.com
http://this.is.even.more.testing.at.test.com

The following mod_rewrite recipe achieves this:

ServerAlias *.yourdomain.com
RewriteEngine On
RewriteCond %{HTTP_HOST} .*.yourdomain.com [NC]

Substitute yourdomain.com with the domain you’re using.

You can also redirect request to folders:

http://blog.test.com – points to http://test.com/blog

To do this, add the following line to the above example:

RewriteRule ^/(.*)$ /var/www/html/%{HHTP_HOST}/$1 [L]

Change the /var/www/html path to match your system configuration.

For this to work, you’ll need a wildcard DNS record for the domain (easy to setup if you control your own DNS).

If you’d like to find out more about mod_rewrite, check out:

The mod_rewrite forum

mod_rewrite: A Beginner’s Guide to URL Rewriting

URL rewriting tutorial at HTMLSource

mod_rewrite cheat sheet

Related Posts