Virtual Subdomains and PHP
October 12th, 2006With the ever dynamic web world and to turn the web from a passive to an active entity , webmasters are fascinated with the idea of having subdomains for users like http://username.domain.com. Looks quite neat and tricky. So lets see how we can achieve this with apache and some PHP.
First i go in my server and change the DNS zone for the requested domain , lets say abc.com. On WHM you can accomplish this easily by going into WHM , then clicking Edit DNS Zone, this will show you the list of DNS zones available on the server , from the list choose abc.com , click Edit. Now you will see various DNS entries for abc.com , in an empty box at the bottom , add a wildcard (*) CNAME entry something like this..
* 14400 IN CNAME abc.com.
If you are not using WHM , you will have to manually find the DNS zone file for abc.com on your server and edit it to take effect like above.
Now what we have done is , we have created a wild card subdomain , meaning that if the subdomain requested doesnt exist , this wild card subdomain will catch it , you can also call this a Catch-All subdomain.
Next i go and edit my httpd.conf file and add a virtual host something like this…
<VirtualHost 11.11.11.11>
ServerAlias *.abc.com
ServerAdmin admin@abc.com
DocumentRoot /home/abc/public_html/subdomains
ServerName *.abc.com
User abc
Group abc
</VirtualHost>
In above block what i have done is , i have pointed the requests for *.abc.com to a different folder than the main domain , this folder can be inside your main domain folder as well , in my case the folder is inside the main domain folder and is called “subdomains”. So any subdomain that is not actually found in the DNS entry will point to this entry in the httpd.conf file and that in turn will point to the folder /home/abc/public_html/subdomains .
Now after doing the above you can put anything inside subdomains folder i.e example.php and you can call this via your browser like this. http://anything.abc.com/example.php , works good , eh?
Now what i will do inside my example.php is ….
$exp = explode(”.”, $HTTP_HOST) ;
$username = $exp[0];
Now what we have done above is , exploded the HTTP_HOST variable and found the username. Once we have that , we can bring in the rest of the data based on it from the DB.The best thing about this approach is that it doesnt overload the DNS server with 100s of subdomain entries.
I find this a very easy and usefull approach , hope this helps someone else as well. Have fun!
Posted by Sab
Ok great Google got YouTube as well , now what next? I wish they would buy Microsoft one day! 