What are virtual hosts?

apacheUsing Apache virtual hosts, allows you to present multiple websites, from one server, effectively having multiple virtual hosts, on one physical host.  This article describes the process of creating virtual hosts.

Visit the apache site for more information. 

Document Root

Start by creating a new document root directory, for the new virtual host website files.  Please note that this article assumes that you've changed the default document root from /var/www to /apache/www.

$ sudo mkdir -p /apache/www/example.com/public_html

Using the -p switch, will create any necessary parent directories in one go.  I've used example.com as the domain, but you will want to put your own domain name here.

Next we will make sure that the apache service owns the public_html directory.

$ sudo chown www-data:www-data -R /apache/www/example.com/public_html

Now we can add a test index.html file to store in the document root.

$ vi /apache/www/example.com/public_html/index.html

You could add <p>Hello World</p> as a test line in your index.html file.


Create Virtual Host

Now we can create the new virtual host.  We will start by copying the default configuration file...

$ sudo cp /etc/apache2/sites-available/default /etc/apache2/sites-available/example.com

Now lets open the config file for editing...

$ sudo vi /etc/apache2/sites-available/example.com

...and we need to add the server name by entering the following line, under the ServerAdmin line (you can also add an alias if you want to)...

ServerName example.com

ServerAlias www.example.com

In the same file, we need to change the document root path.

DocumentRoot /apache/www/example.com/public_html

If you want to use .htaccess files, you will need to change AllowOverride from None to All, in the root Directory section, and the /apache/www directory.

AllowOverride All

AllowOverride All

We can now save the new config file, and activate the virtual host, and restart the apache service...

$ sudo a2ensite example.com

$ sudo service apache2 reload


Thanks for visiting.