How to Set Up an Apache Virtual Host?
Setting up a virtual host in Apache allows you to host multiple websites or domains from a single server instance. By configuring separate directory roots and configuration files, Apache can direct incoming traffic to the correct website based on the requested domain name. This guide outlines the essential steps to create a basic virtual host on a Linux-based Apache server, covering directory creation, configuration file setup, and enabling the new site.
Step 1: Create the Directory Structure
First, you need to create a directory where the website’s files will
live. This is known as the Document Root. Replace
example.com with your actual domain name.
sudo mkdir -p /var/www/example.com/public_htmlNext, assign ownership of the directory to the current user so you can modify files without root privileges, while ensuring the web server can still read them.
sudo chown -R $USER:$USER /var/www/example.com/public_html
sudo chmod -R 755 /var/wwwStep 2: Create a Sample Index Page
To test the configuration later, create a simple HTML file inside your new document root.
nano /var/www/example.com/public_html/index.htmlPaste the following basic HTML code into the file, then save and close it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to Example.com</title>
</head>
<body>
<h1>Success! The example.com virtual host is working!</h1>
</body>
</html>Step 3: Create the Virtual Host Configuration File
Apache stores virtual host configuration files in the
sites-available directory. Create a new file named after
your domain.
sudo nano /etc/apache2/sites-available/example.com.confAdd the following configuration block. This tells Apache to listen
for requests on port 80 and map example.com to the
directory you created.
<VirtualHost *:80>
ServerAdmin admin@example.com
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public_html
ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined
</VirtualHost>Step 4: Enable the Virtual Host
With the configuration file in place, use the Apache companion tools to enable the new site and disable the default placeholder configuration if it is no longer needed.
sudo a2ensite example.com.conf
sudo a2dissite 000-default.confStep 5: Test and Restart Apache
Before restarting the web server, always test the configuration syntax to ensure there are no errors that could take the server offline.
sudo apache2ctl configtestIf the output reads Syntax OK, restart the Apache
service to apply the changes.
sudo systemctl restart apache2You can now point your web browser to your domain name to see the sample index page you created.