How to setup name-based Virtual Hosts on Ubuntu 13.10 and Apache 2.4.6

Let’s imagine you have a project named myvhost-www within the folder /var/www. If you want to access it through your browser the URL would be http://localhost/myvhost-www/

Would not it be better to use the URL To do so you will need to use a name-based Virtual Host.

With name-based virtual hosting, the server relies on the client to report the hostname as part of the HTTP headers. Using this technique, many different hosts can share the same IP address (which is the case for your personal computer).

Step 1: Create a Virtual Host configuration file

Create the file myvhost.conf within /etc/apache2/sites-available folder.

The configuration file MUST have a .conf extension
$ cd /etc/apache2/sites-available
# create an empty file
$ sudo touch myvhost.conf
# Edit it
$ sudo vi myvhost.conf

Within this file insert the following content:

<VirtualHost *:80>
        DocumentRoot "/var/www/myvhost-www"
Inside each block, you will need at minimum a ServerName directive to designate which host is served and a DocumentRoot directive to show where in the filesystem the content for that host lives. In the normal case where any and all IP addresses on the server should be used, you can use * as the argument to NameVirtualHost (In this usual case, this will be “*:80”).

Step 2: Enable the Virtual Host

# Enabling site myvhost
$ sudo a2ensite myvhost.conf

# To activate the new configuration, you need to run:
$ sudo service apache2 reload

If you go check on the sites-enabled folder you will see that your new virtual host is enabled and point to the file we created previously.

$ cd /etc/apache2/sites-enabled
$ ll
lrwxrwxrwx 1 root root   31 Mar  8 18:47 myvhost.conf -> ../sites-available/myvhost.conf

Step 3: Register the Virtual Host to the hosts file

The hosts file is a computer file used by an operating system to map hostnames to IP addresses.

$ sudo vi /etc/hosts

Add the following line to this file:
Entries in the hosts file will have precedence over DNS by default which means that even if domain name exist it will not attempt to look up the record in DNS.

Step 4: Enable mod_rewrite

mod_rewrite provides a way to modify incoming URL requests, dynamically, based on regular expression rules. This allows you to map arbitrary URLs onto your internal URL structure in any way you like.

sudo a2enmod rewrite

You have now configured a Virtual Host and are able to point to and see the same content as on http://localhost/myvhost-www/