Content with Style

Web Technique

Shell script for adding virtual hosts in Leopard

by Pascal Opitz on February 8 2009, 08:22

I was getting annoyed with constantly editing config files myself. That's why I hacked together a shell script to add the vhosts for me.

Prerequisites

Open the Terminal and execute the following commands:


sudo sed -i -e s@^#Include\ /private/etc/apache2/extra/httpd-vhosts.conf@Include\ /private/etc/apache2/extra/httpd-vhosts.conf@ /private/etc/apache2/httpd.conf

This will enable the vhost include file to be read from the httpd conf.


sudo sed -i -e s/^\</#\</ /private/etc/apache2/extra/httpd-vhosts.conf
sudo sed -i -e s/^\ /#\ / /private/etc/apache2/extra/httpd-vhosts.conf
sudo sed -i -e s/^#NameVirtualHost/NameVirtualHost/ /private/etc/apache2/extra/httpd-vhosts.conf

This will enable the Virtualhosts in apache.
Now let's enable PHP as well:


sudo sed -i -e s@^#LoadModule\ php5_module@LoadModule\ php5_module@ /private/etc/apache2/httpd.conf

All we need to do is restart apache:


sudo apachectl restart

Adding a vhost

Now we're all set, and can create the shell script in some location of your choice. In the example below it's assumed that it is called add.sh.

The shell script itself:


#!/bin/sh
#
# Script to validate files in directory
#
add_host_entry() {
	echo "127.0.0.1	$1" >> /etc/hosts
}

add_vhost_conf() {
	cat localvhost.tpl | sed "s/{VHOSTNAME}/$1/" | sed "s@{VHOSTDIRECTORY}@$2@" >> /private/etc/apache2/extra/httpd-vhosts.conf
}

if [ $# -lt 2 ]; then
	echo "syntax: sh add.sh vhostname vhostdir"
	exit
fi

add_host_entry $1
add_vhost_conf $1 $2

The template file 'localvhost.tpl' needs to sit in the same folder like 'add.sh':


#VHOSTSTART {VHOSTNAME}
<VirtualHost *:80 >
	DocumentRoot "{VHOSTDIRECTORY}"
	ServerName {VHOSTNAME}
	ErrorLog /private/var/log/apache2/{VHOSTNAME}-error_log
	CustomLog /private/var/log/apache2/{VHOSTNAME}-access_log common
</VirtualHost>

<Directory {VHOSTDIRECTORY}>
	Options Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
	AllowOverride All
	Order allow,deny
	Allow from all
</Directory>
#VHOSTEND {VHOSTNAME}

You should now be able to add vhosts by typing:


cd /path/to/shellscript/folder
sudo add.sh vhostname /path/to/vhost/webroot

Once you're done do an apache restart again:


sudo apachectl restart

Comments

  • Or you could use something like VirtualHostX to do all that for you. :)

    by Matthew Pennell on February 9 2009, 09:28 #

  • I haven't tried that yet, but I was aware of it. I personally enjoy writing shell scripts, and maybe someone is short of the 9 dollars it costs ...

    by Pascal Opitz on February 9 2009, 09:33 #