[Script] Automate Alias Creation on Apache

About

This is a basic script that allows you to add aliases to an Apache config in which HTTP & HTTPs virtualhosts have already been set. I wrote the script to automate SAAS  processing. You can, however, customize it the way you wish.

Usage

Specify in setalias.sh the main vh that will be used as reference:

vh=”/etc/apache2/sites-available/saas.example.com.conf” main=”saas.example.com”

Then run your command:

setalias.sh add saas2.example.com

or

setalias.sh remove saas2.example.com


This adds basically a new host to the ServerAlias directive.

<VirtualHost *:80>
	...
    ServerName saas.example.com
    ServerAlias saas1.example.com 

	...

</VirtualHost>

<VirtualHost *:443>
	...
    ServerName saas.example.com
    ServerAlias saas1.example.com

	...
	
</VirtualHost>

setalias.sh

#!/usr/bin/env bash

if [ "$(whoami)" != 'root' ]; then
	echo "You have to execute this script as root user"
exit 1;


vh="/etc/apache2/sites-available/saas.example.com.conf"
main="saas.example.com"

if [ $# -eq 2 ]; then
    if [ "$1" = "add" ]; then
		  echo "Adding $2 to $main"
		  grep -rl 'ServerAlias' $vh | xargs sed -i "s/ServerAlias/ServerAlias $2/g"
		  echo `service apache2 reload`
		  logger "[Script] setAlias > Adding $2 to $vh"
    elif [[ "$1" == "delete" || "$1" == "remove" ]]; then
		  echo "Removing $2 from $main"
		  grep -rl $2 $vh | xargs sed -i "s/ $2//g"
		  echo `service apache2 reload`
		  logger "[Script] setAlias > Adding $2 to $vh"
    else
    	echo "[Error] First argument is unknown."
    fi
else
   echo "[Error] Check again your arguments."
fi

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *