Overview
To setup virtual hosts on Apache the standard procedure is the following:
- First, create the directories of the document root for each site
- In the directory /etc/apache2/sites-available, create a configuration entry for each site you want to host. This entry initially could be a copy of default.conf or default-ssl.conf that are provided with apache. You can choose which file to copy based on whether you want to use SSL or not.
- Once the files have been edited, you can enable or disable the sites with the commands a2ensite and a2dissite. Normally you should only make changes to the sites-available directory and not to the sites-enabled directory.
- If a site is enabled but you make changes to its conf file, you can use reload to force apache to reread the files and apply changes.
- If you want to setup subdomains you need to configure DNS appropriately.
Useful commands
Check the syntax of conf files
sudo apachectl configtest
Check the status of apache process
sudo apachectl -S
Example
Let’s say we want to host two sites: site1.local and site2.local that will not use SSL.
Step 1 – Create directories for each site
For each site, create a separate directory in /var/www. These are the directories where you are going to deploy the sites on:
sudo mkdir /var/www/site1.local
sudo mkdir /var/www/site2.local
Step 2 – Duplicate default conf
Copy from the directory /etc/apache2/sites-available either default.conf or default-ssl.conf as templates for the new sites:
cd /etc/apache2/sites-available
sudo cp 000-default.conf site1.local.conf
sudo cp 000-default.conf site2.local.conf
Step 3 – Edit conf files
Edit the files accordingly. It’s better to at least set the ServerName and DocumentRoot. For example:
For site1 (site1.local.conf):
<VirtualHost *:80>
ServerName site1.local
ServerAlias www.site1.local
ServerAdmin webmaster@localhost
DocumentRoot /var/www/site1.local
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
For site2 (site2.local.conf):
<VirtualHost *:80>
ServerName site2.local
ServerAlias www.site2.local
ServerAdmin webmaster@localhost
DocumentRoot /var/www/site2.local
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Step 4 – Configure DNS
At this point you need to configure DNS.
For remote setup you need to add CNAME or A records to the zone.
For local setup you can simply edit your hosts file and append lines for the domains you want to use locally:
127.0.0.1 localhost
127.0.1.1 ...
127.0.0.1 site1.local
127.0.0.1 site2.local
...
Step 5 – Enable the sites
Enable the sites with a2ensite command:
sudo a2ensite site1.local.conf
sudo a2ensite site2.local.conf
If you change your mind you can disable the sites with a2dissite command:
sudo a2dissite site1.local.conf
sudo a2dissite site2.local.conf
Step 6 – Reload configuration
sudo service apache2 reload