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

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

  • 2 min

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

In the previous post, we saw how to set up an Apache server. In that 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, this way 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 -RUSER /var/www/example.com/html sudo chmod -R 755 /var/www

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>
Copied!

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{APACHE_LOG_DIR}/access.log combined

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.