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 myvhost.com? 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
$ 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> ServerName myvhost.com DocumentRoot "/var/www/myvhost-www" </VirtualHost>
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:
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 myvhost.com and see the same content as on http://localhost/myvhost-www/