KevinMehall »

Easily Test Web Sites Locally with Apache VHosts

When developing and testing web sites, I set up temporary fake domains like example.local using /etc/hosts and map them to directories using Apache's Virtual Host feature. This allows each site to have its own root directory rather than being in a subdirectory of localhost, allowing the use of paths relative to / .

Here's a little script to make setting up localhost virtual servers on Apache easier:

#!/bin/bash
# http://blog.kevinmehall.net/2009/apache-local-vhosts
# public domain

echo "127.0.0.1 $1" >> /etc/hosts
cat >> "/etc/apache2/sites-enabled/$1" << EOF
<VirtualHost *>
DocumentRoot $2
ServerName $1
</VirtualHost>
EOF

/etc/init.d/apache2 reload

Put it in /usr/local/bin/add-local-server and sudo chmod +x /usr/local/bin/add-local-server.

Run with sudo add-local-server example.local /path/to/server/root.
It adds an entry in /etc/hosts, sets up a config file for Apache, and then reloads the Apache configuration.

Tested on Ubuntu; may require modification for other distros.

Removing the sites must be done manually:

  1. Remove the entry from /etc/hosts
  2. Delete the file in /etc/apache2/sites-enabled
Like this post? Share/Save/Bookmark or Subscribe
blog comments powered by Disqus