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} !^ [NC]
RewriteCond %{HTTP_HOST} ^(www.)?([^.]+)$ [NC]
RewriteRule ^([^.]+)$ /some_file.php/$1?subdomain=%2 [L,QSA]

The first RewriteCond statement checks if the current host name is not 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.