[Simple Script] Set Up Virtual Hosts On Ubuntu


New Member
Not sure if this would be of any use to people who do this day in and day out, but for me it saves a few minutes when setting up a new domain on a server.

Two files, one the script and one the blank template that is used to create the entry to sites-available.

Stick 'template' in /etc/apache2/sites-available:

<VirtualHost *:80>
ServerName www.DOMAIN
ServerAlias DOMAIN
# Indexes + Directory Root.
DirectoryIndex index.html index.htm index.php
DocumentRoot /home/DOMAIN/htdocs/
# CGI Directory
ScriptAlias /cgi-bin/ /home/DOMAIN/cgi-bin/
<Location /cgi-bin>
Options +ExecCGI
# Logfiles
ErrorLog /home/logs/DOMAIN-error.log
CustomLog /home/logs/DOMAIN-access.log combined

Stick the script 'create.sh' anywhere you want:

echo "Domain name to set up: "
read domainname
cd /etc/apache2/sites-available
sed s/DOMAIN/$domainname/g template > $domainname
if [ ! -d "/home/logs" ]; then
        mkdir /home/logs
mkdir /home/$domainname
mkdir /home/$domainname/htdocs
mkdir /home/$domainname/cgi-bin
touch /home/$domainname/htdocs/index.html
chown -R www-data.www-data /home/$domainname
a2ensite $domainname
service apache2 restart

Like I said, its simple and is a starting point to get a domain up quickly. You can then add on whatever bits you need to after. In the script the group/user is set to www-data but set that to whatever you want.

Apologies if the code is a little suspect, I am new to bash scripting so playing and learning at the same time!