Skip to content

Instantly share code, notes, and snippets.

@aamnah aamnah/vhost.sh
Last active Jul 1, 2019

Embed
What would you like to do?
Bash script to create virtual host file
#!/bin/sh
############
# Author: Aamnah
# URL: http://aamnah.com
# Based on: https://www.linode.com/docs/websites/hosting-a-website
############
# Reset
Color_Off='\033[0m' # Text Reset
# Regular Colors
Red='\033[0;31m' # Red
Green='\033[0;32m' # Green
Yellow='\033[0;33m' # Yellow
Blue='\033[0;34m' # Blue
Purple='\033[0;35m' # Purple
Cyan='\033[0;36m' # Cyan
domain=$1
usage() {
echo "Usage: please provide a domain name (FQDN)"
}
#SCRIPT
disableDefault() {
# Disable the default Apache virtual host
sudo a2dissite *default
}
enableSite() {
# Enable site
sudo a2ensite ${domain}.conf
}
restartApache() {
# Restart Apache
sudo service apache2 restart
}
createFiles() {
# Make directories
sudo mkdir /var/www/${domain}
sudo mkdir /var/www/${domain}/public_html
sudo mkdir /var/www/${domain}/log
sudo mkdir /var/www/${domain}/backups
}
createConf() {
# create virtual host file
sudo touch /etc/apache2/sites-available/${domain}.conf
# add config
echo -e "# domain: ${domain}
# public: /var/www/${domain}/public_html/
<VirtualHost *:80>
# Admin email, Server Name (domain name), and any aliases
ServerAdmin webmaster@${domain}
ServerName www.${domain}
ServerAlias ${domain}
# Index file and Document Root (where the public files are located)
DirectoryIndex index.html index.php
DocumentRoot /var/www/${domain}/public_html
# Allow .htaccess and Rewrites
<Directory /var/www/${domain}/public_html>
Options FollowSymLinks
AllowOverride All
</Directory>
# Log file locations
LogLevel warn
ErrorLog /var/www/${domain}/log/error.log
CustomLog /var/www/${domain}/log/access.log combined
</VirtualHost>
" >> /etc/apache2/sites-available/${domain}.conf
}
setPerms() {
chown -R www-data:www-data /var/www
}
testFile() {
touch /var/www/${domain}/public_html/index.html
echo -e "<!DOCTYPE HTML5>
<html>
<head>
<title>Bonjour!</title>
</head>
<body>
<h1>Looks like it's working..</h1>
</body>
</html>" >> /var/www/${domain}/public_html/index.html
}
FILEPATH='/etc/apache2/sites-available/'${domain}'.conf'
if [ $# -eq 0 ]; then
showUsage
else
# check if file already exists and is not empty
if [ -s ${FILEPATH} ]; then
echo -e "${Red}File already EXISTS and is NOT EMPTY${Color_Off}"
#check if file already exists
elif [ -e ${FILEPATH} ]; then
echo -e "${Yellow}File already EXISTS${Color_Off}"
else
createFiles
createConf
enableSite
setPerms
testFile
restartApache
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.