DEV Community

Cover image for Setting up Apache Virtual Hosts on an Ubuntu Server
Javier Gongora
Javier Gongora

Posted on

Setting up Apache Virtual Hosts on an Ubuntu Server

Virtual hosts allow you to host multiple websites on a single server. This can be useful if you want to host multiple websites on a single instance, or if you want to run multiple versions of a website (e.g. staging and production).

In this tutorial, we'll go through the steps of setting up Apache virtual hosts on an Ubuntu server.

1. Install Apache:

First, make sure that Apache is installed on your server. If it's not already installed, you can install it with the following command:

sudo apt-get install apache2
Enter fullscreen mode Exit fullscreen mode

2. Enable Apache's virtual host module:

Next, we need to enable Apache's virtual host module. This can be done with the following command:

sudo a2enmod vhost_alias
Enter fullscreen mode Exit fullscreen mode

3. Create a new virtual host file:

Next, we'll create a new virtual host file for each website that we want to host. These files can be placed in the /etc/apache2/sites-available directory.

To create a new virtual host file, copy the default virtual host file and modify it to suit your needs. For example:

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.conf
Enter fullscreen mode Exit fullscreen mode

Then, open the new virtual host file in a text editor and modify it to specify the document root (i.e. the directory containing the website's files) and the server name:

<VirtualHost *:80>
  ServerName example.com
  ServerAlias www.example.com
  DocumentRoot /var/www/example.com/public_html
  <Directory /var/www/example.com/public_html>
    AllowOverride All
  </Directory>
</VirtualHost>
Enter fullscreen mode Exit fullscreen mode

Be sure to replace example.com with the actual domain name of your website.

4. Enable the new virtual host:

To enable the new virtual host, use the following command:

sudo a2ensite example.com.conf
Enter fullscreen mode Exit fullscreen mode

5. Restart Apache:

Finally, restart Apache to apply the changes:

sudo systemctl restart apache2
Enter fullscreen mode Exit fullscreen mode

That's it! You should now be able to access your website at the specified domain name.

Top comments (0)