Setting Up Virtual Hosts in Apache

Set up a Directory for the Site

This is the “document root” for the site. The default site is, of course, /var/www/html. This new site can be pretty much anywhere, but I’ve been keeping them in that /var/www structure.

For the sake of this document, I’ll call it /var/www/newsite. Populate it with files for the site (index.html, etc.), set permissions (if it should not inherit the permissions of its parent directory), etc.

Create DNS Entry

Presumably, the host (we’ll call it webserver.mydomain.com) already has an A record. For the new site, a CNAME record pointing to that server will need to be created. For this document, the CNAME host will be newsite; the new URL, newsite.mydomain.com.

Create the Virtual Host File

This is the file that tells Apache about the new site.

  1. Copy the demo file: ’sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/newsite.conf`.
  2. Update the File! Most options are pretty straight-forward. I’m going to cover the key ones here:

The Final newsite.conf

When all is said and done, the newsite.conf file will look like.


	  <VirtualHost *:80>
	  ServerAdmin newsiteadmin@mydomain.com

	  ServerName mydomain.com
	  ServerAlias mysite.mydomain.com

	  DocumentRoot /var/www/newsite

	  ErrorLog ${APACHELOGDIR}/error.log
	  CustomLog ${APACHELOG_DIR}/access.log combined
	  </VirtualHost>

Bring Up the Site

This is pretty straight forward.

  1. Enable the site with a2ensite sudo a2ensite newsite.conf
  2. Restart Apache sudo service apache2 restart

Return to Reference Index

Created by I. Charles Barilleaux
Last Update: 2020-10-11