Posts Tagged ‘apache2’

Vhgen 1.1

Here’s the latest update to my vhgen script for apache2 vhost templating.

Apache Vhost Templating

In Mikamai our deployment platform of choice is Ubuntu Linux. I like a lot the way Apache is set up on Debian based distributions, with the sites-available directory, but nonetheless creating new virtual hosts is a royal PITA.

Today I finally solved the problem once and for all via a super simple ruby templating script. Here it is, it uses a nice gem, optiflags, to parse the commandline arguments:

#!/usr/bin/env ruby
 
require 'rubygems'
require 'optiflag'
 
module MyOptions extend OptiFlagSet
  flag "d" do
    description "The domain name the vhost should serve"
    long_form "domain"
  end
 
  optional_flag "a" do
    description "Email of the admin. If not specified defaults to info@domain"
    long_form "admin"
  end
 
  optional_switch_flag "w" do
    description "Adds www to non www redirection"
    long_form "www_redirect"
  end
 
  and_process!
end
 
flags = MyOptions.flags
 
admin = flags.a ? flags.a : "info@#{flags.d}"
domain = flags.d
quoted_domain = flags.d.gsub(/\./, "\\.")
 
TEMPLATE=<<-EOT
<VirtualHost *:80>
        ServerName #{domain}
        ServerAdmin #{admin} 
 
        DocumentRoot /var/apps/#{domain}
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/apps/#{domain}>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All 
                Order allow,deny
                allow from all
        </Directory>
 
        ErrorLog /var/log/apache2/#{domain}.log
 
        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn
 
        CustomLog /var/log/apache2/#{domain}.log combined
 
</VirtualHost>
EOT
 
REDIRECTION=<<-EOT
<VirtualHost *:80>
  ServerName www.#{domain}
  ServerAdmin #{admin} 
 
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^www\\.#{quoted_domain}
  RewriteRule (.*) http://#{domain}/$1 [R=301,L]
</VirtualHost>
EOT
 
puts TEMPLATE
puts REDIRECTION if flags.w?

I use it like this:

$ vhgen -d domain.com -w > /etc/apache2/sites-available/my_vhost
$ a2ensite my_vhost