Create a Virtual Host for Apache on Ubuntu

Categories:

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, my-test-domain.com

sudo vi /etc/apache2/sites-available/my-test-domain.com.conf

Here is the contents of the file:

<VirtualHost *:80>
    ServerName my-test-domain.com
    ServerAlias www.my-test-domain.com
    ServerAdmin admin@my-test-domain.com
    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
    </Directory>    
    
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

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 *