Dynamic subdomains using .htaccess or mod_rewrite

The man page documentation page for Apache mod_rewrite module says, “Welcome to mod_rewrite, the Swiss Army Knife of URL manipulation!”

Believe me, mod_rewrite lets you do cool things with URLs. You can have one script for every URI request. For uninformed a URI is simply a request for a page or a website like: http://www.kumarchetan.com/blog/all-about-lamp-web-development-blog/ or http://www.shameless-self-promotion.org/about/. In both cases, the websites run WordPress blogging platform and use mod_rewrite. mod_rewrite sends URIs like http://www.shameless-self-promotion.org/about/ or http://www.shameless-self-promotion.org/get los to one server side script or program which knows how to deal with good and bad requests.

But mod_rewrite also lets you play with your domain name and you can have sub-domains on the fly. So you can, without messing up your DNS entries, create sub-domains automagically.  Look at the following mod_rewrite which was added to a .htaccess.

Options +FollowSymLinks
#Turn on the engine
RewriteEngine On
RewriteCond %{HTTP_HOST} ([^.]+)\.domain\.com
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ /%1/$1