Apache2 Virtual Hosts Explained, Step by Step

Virtual hosts let a single Apache server host multiple websites, each with its own domain, document root, and configuration — the standard way to run more than one site on one server.

<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public

    ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
    CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined

    <Directory /var/www/example.com/public>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
sudo a2ensite example.com.conf
sudo apache2ctl configtest   # always check syntax before reloading
sudo systemctl reload apache2

ServerName is what Apache actually uses to decide which virtual host handles an incoming request (via the HTTP Host header) — a missing or mismatched ServerName is the most common reason a new virtual host silently doesn’t get used.