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 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/\_html
sudo chown -R $USER:www-data /var/www/\_html
sudo chmod -R 755 /var/www/

Add an index page (optional):

vim /var/www/\_html/index.php

Create the virtual host config file:

sudo vim /etc/apache2/sites-available/

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

<VirtualHost *:80>

  DocumentRoot /var/www/\_html
  <Directory /var/www/\_html>
    Options -Indexes
    AllowOverride All
    Order Allow,Deny
    Allow from All

  ErrorLog ${APACHE\_LOG\_DIR}/error.log
  CustomLog ${APACHE\_LOG\_DIR}/access.log combined

Now enable the new virtual host and restart Apache:

sudo a2ensite
sudo service apache2 restart

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

Removing a virtual host #

First, disable the virtual host and restart Apache:

sudo rm /etc/apache2/
sudo rm -Rf /var/www/

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/
sudo rm -Rf /var/www/