vhosts_alias Apache Module on Ubuntu Server

roland's picture

Ubuntu Server comes with an interesting way of handling virtualhosts/sites. There are two folders /etc/apache2/sites-available and /etc/apache2/sites-enabled. You can enable and disable using respectively a2ensite and a2disite.

With wildcards introduced into DNS sometime ago, you can take advantage of vhosts_alias modue. You can install it using:

sudo apt-get install libapache2-mod-vhost-hash-alias
sudo a2enmod vhost_alias

The cool thing about this module is that it allows you to easily create subdomains.

To enable your domain you create a file in /etc/apache2/sites-available/www.mydomain.com.conf which can contain something like the virtualhost below, and enable with

sudo a2ensite www.mydomain.com.conf
and finally reload apache with
sudo /etc/init.d/apache2 reload

<VirtualHost *:80>
  ServerName www.mydomain.com
  ServerAlias mydomain.com
  ServerAdmin my.email@mydomain.com
  DocumentRoot /var/www/mydomain/www
  ErrorLog /var/log/apache2/www.mydomain.com.error.log
  CustomLog /var/log/apache2/www.mydomain.com.access.log combined
  <Directory /var/www/mydomain>
    AllowOverride All
  </Directory>
</VirtualHost>

Next, you want to add all sorts of subdomains to show off your projects.

Create another configuration file: /etc/apache2/sites-available/aaa.virtual.mydomain.com.conf . Note the naming of the file, the "aaa" is not chosen in vain. The alphabetical order of the names matters. All your aliased VirtualHost need to come before any other regular VirtualHost. Add something like this in the config file.

<VirtualHost *:80>
  ServerName %1.mydomain.com
  ServerAdmin my.email@email.com
  VirtualDocumentRoot /var/www/mydomain/%1
  ErrorLog /var/log/apache2/virtual.mydomain.com.error.log
  CustomLog /var/log/apache2/virtual.mydomain.com.access.log combined
  <Directory /var/www/mydomain.com/%1/>
    AllowOverride All
  </Directory>
</VirtualHost>

Reload apache as indicated above and you're good to go. You can have as many subdomains as you want. For instance work1.mydomain.com would map to /var/www/mydomain.com/work1. The "%1" part means the first part of the url.

If you have applications based on a framework such as Rails or CakePHP or Django, the root directory of your app is not the folder work1. So, place the folder somewhere else such as /var/www/projects and create a symbolic link to the public/wwwroot directory of your application.

For instance. If I had a Rails app called "mailer", I would put it in /var/www/projects/mailer and then create a symbolic link using:

cd /var/www/mydomain.com
ln -s /var/www/projects/mailer/public mailer

Finally it would be nice if the root of your actual site would be called "www" because both virtualhost would point to it (just to be safe).