Creating a local domain name

When creating a new website is useful to create a local domain name for it too, so that you can use links like /css/style.css. This makes is easier to deploy to your real domain name later.

I like to use a .loc suffix for my local sites.Here’s a bash script that automates the entire process:

#!/bin/bash
# create_local_domain.sh
# @author Richard@TowerWebDesign.co.uk
#
# Configures a local domain on debian machines with apache
# Adds the domain to /etc/hosts
# Creates the apache domain configuration
# Enables the site and restarts apache
 
PROG_NAME=$(basename $0)
DOMAIN=$1
FOLDER=$2
DOMAIN_SUFFIX=.loc
FULL_DOMAIN="$DOMAIN$DOMAIN_SUFFIX"
 
if [ "$#" -ne 2 ]; then		# check both domain name and folder are present
	echo "Usage: $0 site_name domain_name domain_folder"
	exit
fi
 
if [ "$EUID" -ne 1 ]; then
	echo "Please execute as root user"
	echo "Usage: sudo $0 site_name domain_name domain_folder"
	exit
fi
 
echo "Creating local domain $FULL_DOMAIN"
echo "127.0.0.1	$FULL_DOMAIN" >> /etc/hosts
 
# Now create the apache configuration
 
APACHE_FOLDER=/etc/apache2/sites-available/
CONF_SUFFIX=.conf
APACHE_CONFIG_FILE="$APACHE_FOLDER$FULL_DOMAIN$CONF_SUFFIX"
 
touch $APACHE_CONFIG_FILE
echo "<VirtualHost *:80>" >> $APACHE_CONFIG_FILE
echo "	ServerName $FULL_DOMAIN" >> $APACHE_CONFIG_FILE
echo "	DocumentRoot $FOLDER" >> $APACHE_CONFIG_FILE
echo "	<Directory $FOLDER>" >> $APACHE_CONFIG_FILE
echo "		Options Indexes FollowSymLinks MultiViews" >> $APACHE_CONFIG_FILE
echo "		AllowOverride All" >> $APACHE_CONFIG_FILE
echo "		Order deny,allow" >> $APACHE_CONFIG_FILE
echo "		Allow from all" >> $APACHE_CONFIG_FILE
echo "	</Directory>" >> $APACHE_CONFIG_FILE
echo "</VirtualHost>" >> $APACHE_CONFIG_FILE
echo "a2ensite $APACHE_CONFIG_FILE"
a2ensite $FULL_DOMAIN$CONF_SUFFIX
service apache2 reload
 
# Create an html folder and initial index.php file
INDEX_FILENAME=index.php
FULL_INDEX_FILENAME=$FOLDER$INDEX_FILENAME
if [ -d "$FOLDER" ]; then
	echo "$FOLDER already exists ..."
else
	echo "Creating $FOLDER and index.php ..."
	mkdir $FOLDER
	touch $FULL_INDEX_FILENAME
	echo "<!DOCTYPE html>" >> $FULL_INDEX_FILENAME
	echo "<head><title>Holding page for $FULL_DOMAIN</title></head>" >> $FULL_INDEX_FILENAME
	echo "<body><h1>$FULL_DOMAIN coming soon!</h1></body>" >> $FULL_INDEX_FILENAME
fi
 
chmod -R 755 $FOLDER
 
echo "You should now be able to read http://$FULL_DOMAIN in your browser."
echo "Thats all, folks"

Posted on May 14, 2017 at 8:08 am

No Comments