Create a Virtual Host for Apache on Ubuntu


After you installed Apache you can start hosting websites. For each website (domain or subdomain) you will need a Virtual Host. This requires a file that conatins information for Apache to find where the website’s files are on your server, how to access them, where to write the logs, etc.

The Virtual Host configuration files are stored in /etc/apache2/sites-available.
Let’s create a new configuration file for a test domain,

sudo vi /etc/apache2/sites-available/

Here is the contents of the file:

<VirtualHost *:80>
    DocumentRoot /var/www/my-test-domain
    <Directory "/var/www/my-test-domain">
        DirectoryIndex index.php index.html
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

Notice the file extension is .conf. Apache will load all .conf files from /etc/apache2/sites-enabled. We created the file in sites-available, not sites-enabled. We could have just created it directly in the sites-available folder but the more elegant solution is to use the Apache functionality to enable and disable Virtual Hosts (which is actually creating links to the file from sites-available to sites-enabled)

sudo a2ensite my-test-domain

You can also remove links from sites-available to sites-enabled. Below is the command to remove the default Virtual Host:

sudo a2dissite 000-default

Before testing, we need to restart Apache…

sudo systemctl restart apache2

You can now test (if you did not put any files in /var/www/my-test-domain you should get a 404 error).

Leave a Reply

Your email address will not be published. Required fields are marked *