Adding and Removing Virtual Hosts on Ubuntu 14.04

Here's a cheat sheet for working with virtual hosts on an Ubuntu server. The instructions assume you're not logged in as the root user. Change example.com to your own domain/subdomain.

Adding a Virtual Host

Create the directory for your new site and grant permissions. If your user isn't part of the www-data group, you might want to adjust the second line:

sudo mkdir -p /var/www/example.com/public_html
sudo chown -R $USER:www-data /var/www/example.com/public_html
sudo chmod -R 755 /var/www/example.com

Add an index page (optional):

vim /var/www/example.com/public_html/index.php

Create the virtual host config file:

sudo vim /etc/apache2/sites-available/example.com.conf

Here's a very basic example config file you can start with. Paste it in and adjust as necessary:

<VirtualHost *:80>
ServerAdmin admin@example.com
ServerName example.com
ServerAlias www.example.com

DocumentRoot /var/www/example.com/public_html
<Directory /var/www/example.com/public_html>
Options -Indexes
AllowOverride All
Order Allow,Deny
Allow from All
</Directory>

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

 

Now enable the new virtual host and restart Apache:

sudo a2ensite example.com.conf
sudo service apache2 restart

If your DNS is already configured, your site should be available at example.com.

Removing a Virtual Host

First, disable the virtual host and restart Apache:

sudo rm /etc/apache2/sites-available-example.com.conf
sudo rm -Rf /var/www/example.com

At this point, the site is disabled and will no longer be accessible.

Now just remove the config file and cleanup the /var/www/ directory to permanently remove the site and all of its files:

sudo rm /etc/apache2/sites-available/example.com.conf
sudo rm -Rf /var/www/example.com
Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.