Apache virtual hosts allow you to host multiple websites on a single server by configuring separate directories and domain settings. This guide will walk you through setting up virtual hosts on an Ubuntu server with Apache.
Apache virtual hosts enable multiple domains or subdomains to be hosted on the same server. Each virtual host can have its own configuration, document root, and log files.
Each website needs a separate directory to store its files. Create a new directory under /var/www/
:
sudo mkdir -p /var/www/example.com/public_html
Set the correct ownership and permissions:
sudo chown -R $USER:$USER /var/www/example.com/public_html
sudo chmod -R 755 /var/www
Replace example.com
with your actual domain name.
Create a simple HTML file inside the website directory:
nano /var/www/example.com/public_html/index.html
Add the following content:
<html>
<head><title>Welcome to Example.com</title></head>
<body><h1>Success! Apache Virtual Host is working.</h1></body>
</html>
Save and exit (CTRL+X
, then Y
, then Enter
).
Create a new configuration file in the Apache sites-available directory:
sudo nano /etc/apache2/sites-available/example.com.conf
Add the following configuration:
<VirtualHost *:80>
ServerAdmin admin@example.com
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public_html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Save and exit.
Enable the site and reload Apache:
sudo a2ensite example.com.conf
sudo systemctl reload apache2
To disable a virtual host, use:
sudo a2dissite example.com.conf
sudo systemctl reload apache2
If you’re testing on a local machine, update the /etc/hosts
file:
sudo nano /etc/hosts
Add the following line:
127.0.0.1 example.com
Save and exit.
Open a browser and visit http://example.com
. If everything is set up correctly, you should see your test page.
You can also test using curl
:
curl -I http://example.com
If you have an SSL certificate, create a new virtual host configuration:
<VirtualHost *:443>
ServerAdmin admin@example.com
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public_html
SSLEngine on
SSLCertificateFile /etc/ssl/certs/example.com.crt
SSLCertificateKeyFile /etc/ssl/private/example.com.key
SSLCertificateChainFile /etc/ssl/certs/example.com.ca-bundle
</VirtualHost>
Enable the SSL module and restart Apache:
sudo a2enmod ssl
sudo systemctl restart apache2
If Apache doesn't restart, check for syntax errors:
sudo apachectl configtest
If errors appear, correct them in the configuration files and restart Apache:
sudo systemctl restart apache2