What Are Virtual Hosts?
Virtual hosts allow a single Apache server to serve multiple websites, each with its own domain name, document root, and configuration.
Create a Virtual Host
Create /etc/apache2/sites-available/example.com.conf:
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public
<Directory /var/www/example.com/public>
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example.com-error.log
CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
</VirtualHost>Enable the Site
# Create document root
sudo mkdir -p /var/www/example.com/public
echo "<h1>Welcome to Example.com</h1>" > /var/www/example.com/public/index.html
sudo chown -R www-data:www-data /var/www/example.com
# Enable the site
sudo a2ensite example.com.conf
# Disable default site (optional)
sudo a2dissite 000-default.conf
# Test and reload
sudo apache2ctl configtest
sudo systemctl reload apache2PHP-FPM Integration
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example.com/public
<FilesMatch \.php$>
SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost"
</FilesMatch>
</VirtualHost>Enable SSL
sudo a2enmod ssl rewrite
sudo certbot --apache -d example.com -d www.example.comUseful Modules
sudo a2enmod rewrite # URL rewriting (.htaccess)
sudo a2enmod headers # Custom HTTP headers
sudo a2enmod ssl # HTTPS support
sudo a2enmod proxy_fcgi # PHP-FPM support