A short introduction on how to use mod_vhost_alias to host dynamically add virtual hosts to a Apache web server. Once set up this means you can (if your DNS records are configured to support it) add a new subdomain by just creating a new directory on your server.
For this exercise we will be using /usr/home/webhost as the root directory for the hosted websites, that means that any site you add will be placed in a directory inside that directory. There are really only a couple of small changes that need to be made to a somewhat standard Apache install, so read on.
First off we need to make sure that we are loading the mod_vhost_alias module, so open up httpd.conf in your favorite editor, on FreeBSD it generally resides in /usr/local/etc/apache/, on Linux systems it could be pretty much anywhere, but most likely somewhere in /usr/local/.
In httpd.conf you should look for the two following lines:
LoadModule vhost_alias_module libexec/apache/mod_vhost_alias.so AddModule mod_vhost_alias.c
After verifiying that the module is getting loaded we move on to actually adding the dynamic virtualhost directive. This is done by setting UseCanonicalName to Off and then creating a VirtualHost entry that uses mod_vhost_alias. The following code should do, it's important that the code is placed as the first virtualhost entry, at least with Apache 1.3.x as it might otherwise ignore the dynamic virtual hosts completely.
# default to using the domain name that the client supplies UseCanonicalName Off # Use name-based virtual hosts, if you're using another port than 80 then you need to change this. NameVirtualHost *:80 <VirtualHost *> # Load websites from /usr/home/webhost/domainname.tld VirtualDocumentRoot /usr/home/webhost/%0 # Set the log file, where you want to store it and what you want to call it is really up to you CustomLog /var/log/httpd.log common </VirtualHost> # Add any other VirtualHost entries here.
The %0 in the config above tells Apache to use the entire domain name from the address as the directory name, if you're running a large server with lots of domains and subdomains you might choose to do something like /usr/home/%1/%2+ instead in order to keep subdomains in the directory for that specific domain, you can read more about this in the official documentation.
The logfile can be customized to your heart's content, but that's another story for another day, this is what I've got for today. For trickier setups than this one then I once again recommend you read the docs on apache.org, where you can also read up on how to do the same thing I did here but with mod_rewrite.