Virtual Hosts in Apache2 on Ubuntu 14.04

Setting up virtual hosts in apache2 on Ubuntu 14.04 allows a single server to hosts multiple websites. This generally requires four things:

  1. virtual host declarations
  2. creating DocumentRoots for each website to be hosted
  3. enabling each virtual host in Apache2

Virtual Host Declarations

Creating virtual hosts declarations can be done in the /etc/apache2/sites-available folder. Within the /etc/apache2/sites-available folder, a file named “000-default.conf” provides a basic template with which virtual host declarations can be made.

Copy the default file to another file named after the virtual host it will serve.

  • cp 000-default.conf [yourdomain].conf

The new file, [yourdomain].conf, should be edited to look something like this:

<VirtualHost *:80> ServerName [www.yourdomain.com] DocumentRoot /path/to/folder/for/[yourdomain] ServerAdmin [your email] ErrorLog /var/log/apache2/error.log CustomLog /var/log/apache2/access.log combined </VirtualHost>

Repeat the previous steps if more virtual hosts are needed.

Creating DocumentRoots

Each virtual host must have a unique location to store all of the web docs associated with the virtual host. The default location created during the installation of Apache2 is /var/www. While DocumentRoots can exist anywhere in the server’s file system, it’s logical to keep everything in subfolders of /var/www. Thus, folders for each virtual host will be created within /var/www:

  • mkdir /var/www/virthost1 /var/www/virthost2

The command above creates two folders within /var/www called “virthost1″ and “virthost2″ in which the web docs for each virtual host can be placed.

The permissions of the document root folders should be set to 655. However, if rsync is to be used to upload web documents to the document roots, then set folder permissions to 755. All files contained therein can have 644 permissions.

  • chmod 655 /var/www/virthost1

Enabling Virtual Hosts in Apache2

At this point, all that remains is to enable each virtual host within Apache2. The process of enabling the virtual hosts links the information located in /etc/apache2/sites-available to the /etc/apache2/sites-enabled folder. Generally, any edits to the virtual hosts must be done within the sites-available folder, which automatically updates the sites-enabled folder when Apache2 is reloaded. To enable virtual hosts:

  • a2ensite [yourdomain1].conf
  • a2ensite [yourdomain2].conf

Assuming the DNS settings for each virtual host are correct, entering either virtual host’s URL in the address bar of a web browser will display the correct website for each host.