How to setup Apache Virtual Hosts

  • avatar
  • 438 Views
  • 3 mins read

An Apache web server can host multiple websites on the SAME server. You do not need separate server machine and Apache for each website. This can be achieved using the concept of Virtual Host or VHost.
Any domain that you want to host on your web server will have a separate entry in Apache configuration file.

Prerequisites

You will need a running Apache server. If you don't have one check our tutorial on how to Install and configure Apache on Ubuntu.

Create a Virtual Host

You can create a configuration file in the /etc/apache2/sites-available folder, for example the hibit.conf with the following content (replacing hibit.dev with your own domain name):

<VirtualHost *:80>
ServerName www.hibit.dev
ServerAdmin admin@hibit.dev
ServerAlias hibit.dev www.hibit.dev

DocumentRoot /var/www/hibit.dev/html
<Directory /var/www/hibit.dev/html>
Options -Indexes
AllowOverride all
Order allow,deny
allow from all
</Directory>

# Possible values include: debug, info, notice, warn, error, crit, alert, emerg
LogLevel error

ErrorLog ${APACHE_LOG_DIR}/errors.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Let's test if there are any configuration errors through the following command:

$ sudo apache2ctl configtest

apache_config_test.png

Create content folder

Create this directory through the following command, replacing hibit.dev by your respective domain name:

sudo mkdir -p /var/www/hibit.dev/html

Change the directory ownership to current user:

sudo chown -R $USER:$USER /var/www/hibit.dev/html

Assign necessary permissions as follows:

sudo chmod -R 755 /var/www/hibit.dev

Create a dummy test content:

echo "test" > /var/www/hibit.dev/html/index.html

Enable a Virtual Host

Now that we have our virtual host defined, we need to enable it. We can do this by using built-in Apache command:

#Enable the vhost
sudo a2ensite hibit.conf

And disable it in the same way:

#Disable the vhost
sudo a2dissite hibit.conf

In both cases you will need to reload Apache to activate new configuration:

systemctl reload apache2

Define additional Virtual Hosts

To create additional virtual hosts, we must follow all previous steps defining, enabling and applying the specific configuration for each site.

 Join Our Newsletter

Get the latest news and popular articles to your inbox every month

0 Comments

Leave a Reply

Your email address will not be published.