What are Virtual Hosts?
Virtual hosts allow Apache to serve multiple websites from a single server. Each site gets its own configuration with its own domain, document root, and settings.
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>
Options -Indexes +FollowSymLinks
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
sudo chown -R www-data:www-data /var/www/example.com
# Enable site and reload
sudo a2ensite example.com.conf
sudo apache2ctl configtest
sudo systemctl reload apache2Disable Default Site
sudo a2dissite 000-default.conf
sudo systemctl reload apache2Enable Common Modules
sudo a2enmod rewrite # URL rewriting (.htaccess)
sudo a2enmod ssl # HTTPS support
sudo a2enmod headers # Security headers
sudo a2enmod deflate # Compression
sudo systemctl restart apache2