Dynamic Subdomains in Apache

February 27, 2008

Here is an often asked about question when it comes to dedicated hosting. Can you generate dynamic subdomains in Apache? The short answer would be, yes you can! Here is a little more information about the process…

You’ll need to create a virtual host for each subdomain in Apache configuration like:

<VirtualHost *:80>
ServerAdmin webmaster@subdomain1.mydomain.com
DocumentRoot /www/subdomain1.mydomain.com
ServerName subdomain1.mydomain.com
ErrorLog logs/subdomain1.mydomain.com-host.example.com-error_log
CustomLog logs/subdomain1.mydomain.com-access_log common
</VirtualHost>

There is one problem though. If your solution requires folders creation, virtual host addition and apache restarts which does not look good to me. How would I deal with this problem is:

  1. Create a wildcard virtual host for “*.mydomain.com” so that all requests to subdomains go to this virtual host.
  2. Setup a rewrite rule for it to redirect all requests to one page, say index.php
  3. Write up a PHP script taking the hostname the user came to, searching the redirect URL into a storage by it, i.e. mysql db, and redirecting to it. This script will be the index.php script on the wildcard host.

If you use this way, you only need to setup the above once and then add the subdomains in to the storage which appears to be more flexible solution than creating subfolders and modifying Apache configuration.

More Dedicated Web Hosting Help!

2 Responses to “Dynamic Subdomains in Apache”

  1. Katrina Logan Says:

    Hi, it sounds pretty good and looks like, I am onto the right article, which I wanted long. anyways could you please tell me in details abt how to create a subdomain dynamically in php/apache/mysql/linux configuration, with examples [if any], either here or by mail ?
    thanks in advance
    Miltan

  2. Dedicated Diva Says:

    This URL http://www.daniweb.com/forums/thread106772.html might help you out. If you’re still unsure, I’d recommend checking their forums or contacting your web host for further information