Language: EN

como-configurar-un-virtual-host-en-apache-con-raspberry-pi

How to set up a Virtual Host on Apache with Raspberry Pi

We continue with the entries of Raspberry Pi seeing how to configure a Virtual Host on Apache, a convenient improvement to make on our server.

In the previous entry, we saw how to configure an Apache server. In this simple configuration, we used a single IP address or domain, which served files from a single directory.

A Virtual Host is a mechanism that allows the same machine to be associated with different domains or IP addresses. In summary, in this way Apache distinguishes the requested domain or IP and redirects the request to serve the files from different directories.

Although allowing it to work with different domains is its main utility, in any case, configuring a Virtual Host is a measure that favors the maintainability of the system. Therefore, it is convenient to configure it even if initially we only have a domain or IP address.

Create 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 $USER:$USER /var/www/example.com/html
sudo chmod -R 755 /var/www

Create a test file

Next, we will create an example 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 contents

sudo nano /etc/apache2/sites-available/example.com.conf

So that it has the following form

<VirtualHost *:80>
    ServerAdmin admin@example.com
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Enable/disable Virtual Host

Now, to activate our Virtual Host, we use the ‘a2ensite’ command

sudo a2ensite example.com.conf

If, on the other hand, 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, restart Apache to reflect the changes made,

sudo systemctl restart apache2

That’s it! Of course, we could repeat the process with as many domains as necessary. And, as we said, it is a measure that we should perform in any Apache deployment.