Create sites on linode server with bash script

I've found myself doing the same set of tasks every time I want to set up a new website on my Linode server, so I thought I'd turn it into a simple bash script that you keep on the server and run whenever you need to do this.

I've followed the standard instructions from linode's hosting a website docs which are excellent. The script just replaces the example.com entries with a domain that you pass in as a parameter - it's really easy.

Set up bash script

First log into your linode server

Then create a new script file

sudo vim new-site.sh

In this file paste the following

#!/bin/bash

# Add a new site

# If you've got a domain and you want to set up a new site with it
# run this script and pass the new domain as a parameter without a subdomain
# e.g ./new-site.sh -url google.com

# Get address from paramter
DOMAIN=$1
# Set www root directory
wwwroot="/var/www/"

# Create directories
mkdir $wwwroot$DOMAIN

mkdir $wwwroot$DOMAIN/public_html
mkdir $wwwroot$DOMAIN/backups
mkdir $wwwroot$DOMAIN/log

# Create virtual host
cat > /etc/apache2/sites-available/$DOMAIN.conf << EOF

# domain: $DOMAIN
# public: $wwwroot$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 $wwwroot$DOMAIN/public_html
  # Log file locations
  LogLevel warn
  ErrorLog  $wwwroot$DOMAIN/log/error.log
  CustomLog $wwwroot$DOMAIN/log/access.log combined
</VirtualHost>
EOF

# Enable new site
a2ensite $DOMAIN.conf

# Finally restart apache
service apache2 restart

then save the file and close vim

:wq

All done!

Run new site script

To run it just type

sudo ./new-site.sh [domain_name]

e.g.

sudo ./new-site.sh pitchfork.com

All directories should be set up for you and apache restarted. Assuming you've set up the DNS correctly you should then be able to see your new site in your browser.