Creating New Hosts for Apache2

Feb 10, 2013 in Bash

Although creating a new host is not so difficult problem I wrote simple bash script to automate this task. So instead of running several commands in terminal you can simply execute one bash script.

Script will prompt you to input new host name and that's it. You will just need to change desired path to directory where you want the host to be created.

Usage

Run next command in terminal:

$ sudo ./newhost.sh

newhost.sh

Here is the code itself:

#!/bin/bash
VHOST_AVAILABLE=/etc/apache2/sites-available/
ROOT_UID=0
NOTROOT=87
WWW_ROOT=/home/dfsq/prog/sites/
PUBLIC_DIR_NAME=public_html
HOST_IP=127.0.1.1

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

# New host name
clear
read -p "Enter new host name: " newhost

# 1. Create new host directory
mkdir -p -v $WWW_ROOT$newhost"/"$PUBLIC_DIR_NAME
chmod -R 777 $WWW_ROOT$newhost

# 2. Make a copy of the new host configuration file
cp $VHOST_AVAILABLE"default" $VHOST_AVAILABLE$newhost

# Extract default host path
default_path=`sed -n 's/.*DocumentRoot\s\(.*\)\s*/\1/p' $VHOST_AVAILABLE$newhost`

# Server name
_s="ServerName\\s\\+.\\+"
_r="ServerName $newhost"
sed -i "s/${_s}/${_r}/g" $VHOST_AVAILABLE$newhost

# Write new DocumentRoot
_s=$default_path
_r=$WWW_ROOT$newhost"/"$PUBLIC_DIR_NAME
_s="${_s//\//\\/}"
_r="${_r//\//\\/}"
sed -i "s/${_s}/${_r}/g" $VHOST_AVAILABLE$newhost

# Change error.log path
_s="ErrorLog\\s\\+.\\+"
_r="ErrorLog "$WWW_ROOT$newhost"/error.log"
_r="${_r//\//\\/}"
sed -i "s/${_s}/${_r}/g" $VHOST_AVAILABLE$newhost

# 4. Enable new host
a2ensite $newhost

# 5. Update host file
echo -e "$HOST_IP\t$newhost" >> /etc/hosts

# 6. Restart apache
/etc/init.d/apache2 reload

echo "Host $newhost created."

exit;

END

That's it. You can also copy newhost.sh to /usr/local/bin/newhost so that you could call it simply newhost from any location.

Happy codding!

comments powered by Disqus