How To Set Up Apache Virtual Hosts on Ubuntu Linux

You will need to have Apache installed in order to work through these steps. If you haven’t already done so, you can get Apache installed on your server through apt-get:

sudo apt-get update
sudo apt-get install apache2

For example let’s create virtual Apache host test.host. Create host directory:

sudo mkdir -p /var/www/test.host/public_html

Now we have the directory structure for our files, but they are owned by our root user. If we want our regular user to be able to modify files in our web directories, we can change the ownership by doing this:

sudo chown -R $USER:$USER /var/www/test.host/public_html

We should also modify our permissions a little bit to ensure that read access is permitted to the general web directory and all of the files and folders it contains so that pages can be served correctly:

sudo chmod -R 755 /var/www

Virtual host files are the files that specify the actual configuration of our virtual hosts and dictate how the Apache web server will respond to various domain requests.

Apache comes with a default virtual host file called 000-default.conf that we can use as a jumping off point. We are going to copy it over to create a virtual host file for each of our domains.

We will start with one domain, configure it, copy it for our second domain, and then make the few further adjustments needed. The default Ubuntu configuration requires that each virtual host file end in .conf. Start by copying the file for the first domain:

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/test.host.conf

Open the new file in your editor with root privileges:

sudo nano /etc/apache2/sites-available/test.host.conf

Change this file look something like this:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName test.host
    ServerAlias www.test.host
    DocumentRoot /var/www/test.host/public_html

    <Directory /var/www/test.host/public_html>
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Now that we have created our virtual host files, we must enable them. Apache includes some tools that allow us to do this.

sudo a2ensite test.host.conf

Next, disable the default site defined in 000-default.conf:

sudo a2dissite 000-default.conf

When you are finished, you need to restart Apache to make these changes take effect:

sudo service apache2 restart