18 January 2013

create subdomains using htaccess

Its very quick and easy. Here we go

  1. You need to create a wildcard domain on your DNS server *.website.com 
  2. Then in your vhost container you will need to specify the wildcard aswell *.website.com - This is done in the ServerAlias DOCs 
  3. Then extract and verify the subdomain in PHP and display the appropriate data
Here we go in some detail.
  • Create a wildcard DNS entry - In your DNS settings you need to create a wildcard domain entry such as *.example.com. A wildcard entry looks like this:
     *.example.com.   3600  A
  • Include the wildcard in vhost - Next up in the Apache configuration you need to set up a vhost container that specifies the wildcard in the ServerAlias DOCs directive. An example vhost container:
      ServerName server.example.com
      ServerAlias *.example.com
      UseCanonicalName Off
  • Work out which subdomain you are on in PHP - Then in your PHP scripts you can find out the domain by looking in the $_SERVER super global variable. Here is an example of grabbing the subdomain in PHP:
    preg_match('/([^.]+)\.example\.com/', $_SERVER['SERVER_NAME'], $matches);
    if(isset($matches[1])) {
        $subdomain = $matches[1];
    I have used regex here to to allow for people hitting your site via www.subdomain.example.com or subdomain.example.com.
    If you never anticipate having to deal with www. (or other subdomains) then you could simply use a substring like so:
    $subdomain = substr(
                     $_SERVER['SERVER_NAME'], 0,
                     strpos($_SERVER['SERVER_NAME'], '.')
I did it in php. For java or dot net, you need to change my php code to respective java or dot net code.

1 comment:

  1. This is a very nice article on htaccess i like your article.