Beta 42

Research and Development

Menu

Setup Apache Virtual Hosts

The term Virtual Host refers to the practice of running more than one web site on a single machine. Virtual hosts can be IP-based (different IP address for every web site), or name-based (multiple names running on a single IP address). The fact that the websites are running on the same physical server is not apparent to the end user.

Here we focus on name-based virtual hosts.

Create the directory for your_domain as follows:

sudo mkdir /var/www/your_domain

Next, assign ownership of the directory to Apache user www-data:

sudo chown -R www-data:www-data /var/www/your_domain

Create a sample index.html page:

sudo vim /var/www/your_domain/index.html

Inside, add the following sample HTML code:

<html>
    <head>
        <title>Welcome to Your_domain!</title>
    </head>
    <body>
        <h1>Success!  The your_domain server block is working!</h1>
    </body>
</html>

In order for Apache to serve this content, it’s necessary to create a virtual host file with the correct directives. Instead of modifying the default configuration file located at /etc/apache2/sites-available/000-default.conf directly, let’s make a new one at /etc/apache2/sites-available/your_domain.conf:

sudo vim /etc/apache2/sites-available/your_domain.conf

Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName your_domain
    ServerAlias www.your_domain
    DocumentRoot /var/www/your_domain
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Edit apache2.conf file and add ServerName localhost at the bottom:

sudo vim /etc/apache2/apache2.conf

Enable the file with the a2ensite tool:

sudo a2ensite your_domain.conf

Disable the default site defined in 000-default.conf:

sudo a2dissite 000-default.conf

Next, test for configuration errors:

sudo apache2ctl configtest

Restart Apache to implement your changes:

sudo systemctl restart apache2

Apache should now be serving your domain name. You can test this by navigating to http://your_domain.