Apache Virtual Hosts Guide

Virtual hosts allow you to host multiple websites on a single server. This guide will help you understand how to set up and manage Apache virtual hosts.

What is a Virtual Host?

A virtual host is a configuration that allows a web server to host multiple websites using a single IP address. Each virtual host can have its own domain name, document root, and configuration settings.

Types of Virtual Hosts

There are two types of virtual hosts:

  • Name-based virtual hosts: These use the domain name to identify the virtual host. The server looks at the Host header of the incoming request to determine which virtual host to serve.
  • IP-based virtual hosts: These use the IP address to identify the virtual host. Each virtual host must have a unique IP address assigned to it.

Setting Up Name-based Virtual Hosts

To set up a name-based virtual host, you need to do the following:

  1. Create a new virtual host configuration file: Place the file in the /etc/apache2/sites-available/ directory.
  2. Edit the configuration file: Add the following lines to the file:
<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName example.com
    DocumentRoot /var/www/example.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
  1. Enable the virtual host: Use the a2ensite command to enable the virtual host.
sudo a2ensite example.com.conf
  1. Restart Apache: Use the systemctl command to restart Apache.
sudo systemctl restart apache2

Setting Up IP-based Virtual Hosts

To set up an IP-based virtual host, you need to do the following:

  1. Assign a unique IP address to your server: Use the ifconfig or ip command to assign a unique IP address to your server.
  2. Create a new virtual host configuration file: Place the file in the /etc/apache2/sites-available/ directory.
  3. Edit the configuration file: Add the following lines to the file:
<VirtualHost 192.168.1.10:80>
    ServerAdmin webmaster@localhost
    ServerName example.com
    DocumentRoot /var/www/example.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
  1. Enable the virtual host: Use the a2ensite command to enable the virtual host.
sudo a2ensite example_ip.conf
  1. Restart Apache: Use the systemctl command to restart Apache.
sudo systemctl restart apache2

For more information on Apache virtual hosts, visit our Apache Virtual Hosts Documentation.

Apache Server