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:
- Create a new virtual host configuration file: Place the file in the
/etc/apache2/sites-available/
directory. - 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>
- Enable the virtual host: Use the
a2ensite
command to enable the virtual host.
sudo a2ensite example.com.conf
- 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:
- Assign a unique IP address to your server: Use the
ifconfig
orip
command to assign a unique IP address to your server. - Create a new virtual host configuration file: Place the file in the
/etc/apache2/sites-available/
directory. - 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>
- Enable the virtual host: Use the
a2ensite
command to enable the virtual host.
sudo a2ensite example_ip.conf
- 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