I wrote this script out of my need for a quick method of adding virtual domains. I hope you find this to be of great use.

create a file named addomain

  1. sudo vim /usr/bin/adddomain

Place this in your file:

  1. #!/bin/bash
  2. #Edit the following e-mail address:
  3. email="your@email.address"
  4. ipaddress=`ifconfig eth0 | grep inet | awk ‘{print $2}’ | sed ‘s/addr://’ | grep .`
  5. domain=$1
  6. file="/etc/apache2/sites-available/$domain"
  7. if [ -z $domain ]; then
  8.         echo "You did not specify a domain"
  9.         echo "Usage:"
  10.         echo "          adddomain domain.tdl"
  11.         echo ""
  12. else
  13.         ping=`ping -c 1 $domain|grep "$ipaddress"`
  14.         if [ -z $ping ]; then
  15.                 echo "$domain is not hosted on this server, or you have not set up its A record"
  16.         else
  17.                 touch /etc/apache2/sites-available/$domain;
  18.                 echo "# Place any notes or comments you have here
  19. # It will make any customisation easier to understand in the weeks to come
  20. # domain: $domain
  21. # public: /var/virtualwww/$domain
  22.  
  23. <VirtualHost *:80>
  24.  
  25.  # Admin email, Server Name (domain name) and any aliases
  26.  ServerAdmin $email
  27.  ServerName  $domain
  28.  ServerAlias www.$domain
  29.  
  30.  
  31.  # Index file and Document Root (where the public files are located)
  32.  DirectoryIndex index.php
  33.  DocumentRoot /var/virtualwww/$domain
  34.  
  35.  
  36.  # Custom log file locations
  37.  LogLevel warn
  38.  ErrorLog  /var/log/apache2/$domain/error.log
  39.  CustomLog /var/log/apache2/$domain/access.log combined
  40.  
  41. </VirtualHost>" > $file;
  42.                 mkdir /var/log/apache2/$domain;
  43.                 mkdir /var/virtualwww/$domain;
  44.                 ln -s /var/www/.htaccess /var/virtualwww/$domain/.htaccess;
  45.                 mkdir /var/virtualwww/$domain/cgi-bin;
  46.                 echo "created $domain";
  47.                 echo "please restart apache2";
  48.                 a2ensite $domain;
  49.         fi
  50. fi

Next, change the permissions of adddomain:

  1. sudo chmod 500 /bin/bash/adddomain

Once all that is done, create a new folder to house your virtual domains:

  1. sudo mkdir /var/virtualwww

Next, change the adddomain file so it properly points to your .htaccess file (if you have one), and you’re done. To use this script:

  1. adddomain domain.tdl

The server will do a lookup on that domain/subdomain, and if it shows that the server you are on does not have an IP on it that matches the (sub)domains IP, it won’t let you add that site.