Skip to content

Instantly share code, notes, and snippets.

@tommcdo
Last active January 18, 2017 07:18
Show Gist options
  • Save tommcdo/8584985 to your computer and use it in GitHub Desktop.
Save tommcdo/8584985 to your computer and use it in GitHub Desktop.
Quick script to add a local site to your Apache server.
#!/bin/bash
SITE_BASE=/home/tommcdo/sites # Base directory into which sites are installed
LOCAL_TLD=local # TLD for local sites, e.g. http://mysite.local
DOC_ROOT=public_html # Subdirectory of main folder for document root
# Ensure root privileges
if [[ $EUID -ne 0 ]]; then
echo >&2 "This script can only be run as root"
exit
fi
# Ensure site name is given
if [ -z "$1" ]; then
echo >&2 "Usage: $0 SITE"
exit
fi
# Fix up config parameters
DOC_ROOT=${DOC_ROOT:+/$DOC_ROOT}
LOCAL_TLD=${LOCAL_TLD:+.$LOCAL_TLD}
# Get site name
site=$1
# Add site into hosts file
perl -i -lpe "s/(?=# End local sites)/127.0.0.1\t${site}${LOCAL_TLD}\n/" /etc/hosts
# Create directory for site to live in
mkdir -p ${SITE_BASE}/${site}${DOC_ROOT}
chown -R tommcdo:tommcdo ${SITE_BASE}/${site}
# Add virtual host entry
cat <<EOF > /etc/apache2/sites-available/${site}${LOCAL_TLD}.conf
<VirtualHost *:80>
ServerName ${site}${LOCAL_TLD}
DocumentRoot "${SITE_BASE}/${site}${DOC_ROOT}"
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>
</VirtualHost>
EOF
# Enable site and reload Apache
a2ensite ${site}${LOCAL_TLD}.conf
service apache2 reload
# Sample /etc/hosts
# ... regular configuration
# Start local sites
127.0.0.1 mysite.local
# End local sites
# The "End local sites" comment is required
# ... more regular configuration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment