A Virtual Host is a configuration that lets Apache serve different sites from the same server.
In a basic configuration, Apache serves files from a single directory. That is fine for testing, but it quickly falls short when we want to separate projects, domains, or applications.
A Virtual Host allows the same machine to be associated with different domains or IP addresses. In summary, Apache distinguishes the requested domain or IP, and redirects the request to serve files from different directories.
Although allowing it to work with different domains is its main utility, in any case, configuring Virtual Hosts is a measure that favors system maintainability. Therefore, it is advisable to configure it even if initially we only have one domain or IP address.
Create a directory with the files to serve
Create a directory for the content
First, we create a directory where we will store the files to be served, for example ‘/var/www/example.com/html’
sudo mkdir -p /var/www/example.com/html
Next, we need to grant the appropriate permissions to this new folder.
Grant permissions
sudo chown -R
Create a test file
Next, we will create a sample file ‘index.html’ in the directory we just created
nano /var/www/example.com/html/index.html
With the content,
<html>
<head>
<title>Hello world!</title>
</head>
<body>
<h1>This is your web page. Congratulations!</h1>
</body>
</html>
Configure the Virtual Host
Now, we copy the default configuration to a new configuration file,
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.conf
And edit its content
sudo nano /etc/apache2/sites-available/example.com.conf
So that it has the following form
<VirtualHost *:80> ServerAdmin [email protected] ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/html ErrorLog
Enable/disable Virtual Host
Now, to activate our Virtual Host we use the ‘a2ensite’ command
sudo a2ensite example.com.conf
If, on the contrary, we want to disable it, we use the ‘a2dissite’ command. For example, to disable the default server we use
sudo a2dissite 000-default.conf
Restart Apache
Finally, we restart Apache for the changes to take effect,
sudo systemctl restart apache2
That easy! Of course, we could repeat the process with as many domains as necessary. And, as we said, it is a convenient measure that we should implement in any Apache deployment.

