Skip to content

Instantly share code, notes, and snippets.

@plasticbrain
Last active March 12, 2021 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save plasticbrain/9620763 to your computer and use it in GitHub Desktop.
Save plasticbrain/9620763 to your computer and use it in GitHub Desktop.
Bash Script to Add a New Domain
#!/bin/sh
################################################################################
# Bash script to add a new domain (Apache2)
# (c) 2014 Mike Everhart | PlasticBrain Media LLC
#
# Prerequisites:
# Create a vhosts "template" in $APACHEDIR/sites-available. The template should
# include placeholders ($TOKEN) that will be replaced with the new domain name.
# See https://gist.github.com/plasticbrain/9620846 for an example template
#
# Usage:
# ./add_domain.sh domain-to-add.com
#
#################################################################################
APACHEDIR=/etc/apache2
TEMPLATEFILE=_TEMPLATE_
WWWDIR=/var/www
HTMLDIR=public_html
WWWUSER=www-data
WWWGROUP=www-data
TOKEN=%DOMAIN%
DOMAIN=$1
## Make sure a domain was passed
if [ -z $1 ]
then
echo "You did not include the new domain name..."
exit
fi
## Create the directory for the new domain
mkdir -p $WWWDIR/$DOMAIN/$HTMLDIR
echo "+ Created dir $WWWDIR/$DOMAIN/$HTMLDIR"
## Copy the vhosts template
sudo cp $APACHEDIR/sites-available/$TEMPLATEFILE $APACHEDIR/sites-available/$DOMAIN
echo "+ Created vhosts file at $APACHEDIR/sites-available/$DOMAIN"
## Replace the token placeholder with the domain
sudo sed -i "s/$TOKEN/$DOMAIN/g" $APACHEDIR/sites-available/$DOMAIN
echo "+ Replaced \"$TOKEN\" with \"$DOMAIN\" in $APACHEDIR/sites-available/$DOMAIN"
## chown/chmod the vhosts files
sudo chown $WWWUSER:$WWWGROUP $APACHEDIR/sites-available/$DOMAIN
sudo chmod 775 $APACHEDIR/sites-available/$DOMAIN
echo "+ chowned/chmoded vhosts file"
echo "+ Enabling the domain and reloading Apache:"
sudo a2ensite $DOMAIN
sudo service apache2 reload
echo "! Finished! Domain \"$DOMAIN\" was added"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment