LochStudios  /  Help Centre  /  VPS & Linux  /  Set up Apache virtual hosts

Set up Apache virtual hosts

Configure Apache virtual hosts to serve multiple websites from a single server using name-based hosting.

Updated

Virtual hosts allow you to run multiple websites on a single Apache server. This guide covers setting up name-based virtual hosts on Ubuntu/Debian.

Prerequisites

  • Apache2 installed and running
  • One or more domain names (or subdomains) pointing to your server's IP
  • sudo access to the server

Configuration Steps

1. Create directories for your site content

For each website, create a directory to store its files:

sudo mkdir -p /var/www/yourdomain.com/html
sudo mkdir -p /var/www/yourdomain.com/logs

Replace yourdomain.com with your actual domain name.

2. Set proper permissions

sudo chown -R $USER:$USER /var/www/yourdomain.com/html
sudo chmod -R 755 /var/www/yourdomain.com

3. Create a sample index file

echo "<h1>Welcome to yourdomain.com</h1>" | tee /var/www/yourdomain.com/html/index.html

4. Create a virtual host configuration file

sudo nano /etc/apache2/sites-available/yourdomain.com.conf

Paste the following configuration:

<VirtualHost *:80>
    ServerName yourdomain.com
    ServerAlias www.yourdomain.com
    
    ServerAdmin admin@yourdomain.com
    DocumentRoot /var/www/yourdomain.com/html
    
    ErrorLog /var/www/yourdomain.com/logs/error.log
    CustomLog /var/www/yourdomain.com/logs/access.log combined
</VirtualHost>

Replace yourdomain.com with your domain name. Press Ctrl+X, then Y, then Enter to save.

5. Enable the virtual host

sudo a2ensite yourdomain.com.conf

6. Test Apache configuration syntax

sudo apache2ctl -t

You should see Syntax OK.

7. Reload Apache

sudo systemctl reload apache2

8. Verify the site is accessible

In your browser, navigate to http://yourdomain.com (or from the server: curl http://yourdomain.com).

Adding More Virtual Hosts

Repeat steps 1–7 for each additional domain, using different domain names and directory paths.

Disabling a Virtual Host

To disable a virtual host without deleting its config:

sudo a2dissite yourdomain.com.conf
sudo systemctl reload apache2

Tips

  • Virtual host files should be named yourdomain.com.conf for clarity
  • Use ServerAlias to handle both yourdomain.com and www.yourdomain.com
  • Always check sudo apache2ctl -t before reloading to catch syntax errors
  • Log files are separated per domain, making troubleshooting easier
  • For HTTPS (SSL/TLS), use port 443 and add SSLEngine on plus certificate paths

For RHEL/CentOS/Rocky

Use /etc/httpd/conf.d/ instead of /etc/apache2/sites-available/, and reload with sudo systemctl reload httpd.


Was this article helpful?

← Back to VPS & Linux