Creating virtual subdomain with htaccess

Posted on Categories:PHP, MySQL, Symfony, UNIX/Linux in general

In order to create a virtual subdomain in PHP, the following conditions must be fulfilled:
– enabled Apache’s Mod_rewrite module
– existing wildcard DNS record
– properly configured .htaccess file

At this point, it is assumed that you have successfully covered the first two prerequisites.
In .htaccess file, use the following rules to set up the virtual subdomain

# .htaccess

Options +FollowSymLinks
RewriteBase /
 
RewriteCond %{HTTP_HOST} !^www.your-domain-name.com [NC]
RewriteCond %{HTTP_HOST} ^(www.)?([^.]+).your-domain-name.com$ [NC]
RewriteRule ^([^.]+)$ /some_file.php/$1?subdomain=%2 [L,QSA]

The first RewriteCond statement checks if the current host name is not www.your-domain-name.com. Then, if the first condition has been satisfied, the second RewrideCond adds the condition that URL is formed like a subdomain with or withoud the www in front of it.

The RewriteRule does the actual URL rewriting and passes the subdomain in a GET parameter to the some_file.php.

Literature:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewriteflags
http://www.reconn.us/content/view/46/67/
http://corz.org/serv/tricks/htaccess2.php