Bash Script for create Apache virtual hosts quick and easy

Valic —  March 13, 2011 — 3 Comments

Virtual hosts are used to run more than one web site on a single machine.
Virtual hosts can be “IP-based”, meaning that you have a different IP address for every web site, or “name-based”, meaning that you have multiple names running on each IP address.

I want to show you one of mine scripts for easy create virtual hosts in Debian Squeeze or ubuntu.

#!/bin/bash
VHOST_CONF=/etc/apache2/sites-enabled/
ROOT_UID=0
NOTROOT=87
WWW_ROOT=/var/www/

# Check if is root
if [ "$UID" -ne "$ROOT_UID" ]
then
echo “You must be root to run this script.”
exit $NOTROOT
fi

if [ -n "$1" ]
then
DOMAIN=$1
else
echo “You must provide a full domain name for this site, i.e. ‘example.com’ ”
echo -n “Run this script like ./script example.com .”
exit
fi

#Create document root site folder
mkdir -p $WWW_ROOT/$DOMAIN

CONF=”\n\n##################\n# $DOMAIN\n##################\n\n ServerAdmin webmaster@$DOMAIN\n ServerName $DOMAIN\n ServerAlias www.$DOMAIN\n DocumentRoot \”$WWW_ROOT/$DOMAIN\”\n \”\n Options Indexes FollowSymLinks\n AllowOverride All\n Order allow,deny\n Allow from all\n \n ErrorLog /var/log/apache2/$DOMAIN-error_log\n CustomLog /var/log/apache2/$DOMAIN-access_log common\n \n”

echo -e $CONF > $VHOST_CONF/$DOMAIN

echo “$DOMAIN was created. In 5 seconds your apache will be restarted”
sleep 5

apachectl restart

echo “Done”
exit 0

You can download this script directly from HERE
Enjoy.

Valic

Posts Twitter Facebook

Editor in Chief at Debian-Tutorials, Linux enthusiast.

3 responses to Bash Script for create Apache virtual hosts quick and easy

  1. I’ve setup something very similar for a client but I use a file as the template for the vhost configuration and I change some tags into domain name and whatever else is needed. this way the template is easier to read.

    one thing that could make your script friendlier would be to verify the apache config files for syntax before restart with ‘apache2ctl -S’.

    lastly, ‘apache2ctl graceful’ would be better than ‘… restart’ since it doesn’t terminate current connections.

  2. Where can i find this amazing templates based schipt ?

    Thanks!

  3. Hello,
    This script is created by me. Only here you will find it

Leave a Reply