Virtual hosts in Apache allow you to run multiple websites on a single server. This setup is essential for managing different sites with separate domain names or directory structures under a single Apache installation.
Ensure you have Apache installed on your server and that you have root or sudo privileges to make changes.
First, create a directory structure for your website. This helps in organizing your files neatly:
sudo mkdir -p /var/www/example.com/public_html
Make sure to replace example.com
with your actual domain name.
Next, create a configuration file for your virtual host. This file will define how Apache serves your site:
sudo nano /etc/apache2/sites-available/example.com.conf
Add the following content to the file:
<VirtualHost *:80>
ServerAdmin webmaster@example.com
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example.com/public_html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Save and close the file.
Enable the new virtual host file and reload Apache to apply the changes:
sudo a2ensite example.com.conf
sudo systemctl reload apache2
You should now be able to access your site by navigating to your domain name in a web browser.
You've successfully configured a virtual host in Apache. This setup allows you to host multiple websites on a single server, each with its own configuration.