Skip to main content

Apache Virtual Hosts

Setting up Apache Virtual Hosts can become quite tedious if it is frequently repeated.

Wouldn't it be nice if we could automate the process?

Here is where scripting comes to the rescue!

You can use the following Python script to make your life a little easier (Python 3.4 or greater).

It will create the folder structure for every site in the "domains" array (under the "/var/www/html/vhosts" folder), create the necessary Apache config files, modify the "/etc/hosts" file, and restart Apache. The only thing you will have to do, is to navigate to "http://siteName.local/". Isn't that enough?

Save it as

and run it with

sudo python

import os
import subprocess
import socket

domain = raw_input('Please enter the domain name to create: ')
domains = []

# If you want to create multiple vhosts at once, uncomment and use the following code.
# domains = [
# 	'vhost_1',
# 	'vhost_2',
# 	'vhost_3',
# 	'vhost_4',
# 	'vhost_5'
# 	]

def create_dirs():
    ''' Create the directory structure. '''
    for name in domains:
        if not os.path.isdir('/var/www/html/vhosts/' + name):
            os.mkdir('/var/www/html/vhosts/' + name)
            os.mkdir('/var/www/html/vhosts/' + name + '/public_html/')
            os.mkdir('/var/www/html/vhosts/' + name + '/logs/')

            # Enable the site (3.4 Python version)
            os.system("a2ensite " + name + ".local")

            # Enable the site (3.5 Python version)
            #['a2ensite', name + '.local'], check=True)

            # Write to the hosts file.
            print('{0} already exists. Skipping...'.format(name))

    # Restart apache (3.4 Python version)
    os.system("service apache2 restart")

    # Restart apache (3.5 Python version)
    #['service', 'apache2', 'restart'], check=True)

def write_hosts(name):
    ''' Write the hosts file. '''
    ip = [(s.connect(('', 53)), s.getsockname()[0], s.close()) for s in
          [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
    # with open('/media/sf_C_DRIVE/Windows/System32/drivers/etc/hosts', 'a') as file:
    with open('/etc/hosts', 'a') as file:
        file.write('\n{0} {1}.local\n'.format(ip, name))

def create_index_files(name):
    ''' Create the index files. '''
    with open('/var/www/html/vhosts/' + name + '/public_html/index.html', 'w') as file:
        text = '{0}.local has been created successfully.'.format(name)

def create_conf_files(name):
    ''' Create the configuration files at /etc/apache2/sites-available. '''
    with open('/etc/apache2/sites-available/' + name + '.local.conf', 'w+') as file:
        text = """
      # Enable the site with sudo a2ensite site_name && sudo /etc/init.d/apache2 restart
      # Enable the site with sudo a2ensite {0}.local && sudo /etc/init.d/apache2 restart
      ServerName {0}.local
      ServerAdmin webmaster@localhost
      DocumentRoot /var/www/html/vhosts/{0}/public_html/
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
      LogLevel info warn
      ErrorLog /var/www/html/vhosts/{0}/logs/error.log
      CustomLog /var/www/html/vhosts/{0}/logs/access.log combined

def main():
    if os.path.isdir('/var/www/html/vhosts/'):

if __name__ == '__main__':

Alternatively, to delete an existing site that you don't want anymore, you can run the following bash script.


# Create a variable with the sitename.
echo "Provide the name of the vhost you want to delete, followed by [ENTER]:"

read vhost;

# Delete all files associated with this site.
sudo rm -r /var/www/html/vhosts/${vhost};
sudo rm "/etc/apache2/sites-available/${vhost}.local.conf";
sudo rm "/etc/apache2/sites-enabled/${vhost}.local.conf";

# Restart Apache.
sudo service apache2 restart;

echo "The ${vhost} vhost was deleted successfully."

exit 0;


PS: You can contribute at if you wish.