s

Posts Tagged with "apache"

Ruby Script to Add Apache Virtual Host Entry

Aug 10, 2009  -  Comments

When you're working with Rails, you never really have to add a virtual host entry for development (unless you use Passenger). You can always just fire up script/server and navigate to http://localhost:3000.

At my new job, I'm doing a lot of work on PHP and Drupal sites, which require you to add an entry to your host file and add a virtual host conf file for Apache. After only going through this process twice, I was already tired of it. I wrote the following script to automate the process for me.

#!/usr/bin/ruby

########################################
##### VARIABLES YOU NEED TO CHANGE #####
########################################

host_dir  = '/etc/hosts/index.html'            # path to your hosts file
sites_dir = '/Library/Webserver/index.html'    # path to the directory where you keep your sites (NO TRAILING SLASH!!!)
conf_dir  = '/etc/apache2/sites/index.html'    # path to directory where named conf files live

########################################

unless ARGV[0]
  puts "Usage: add_site sitename [hostname_for_url]"
  puts "Example: add_site sample sample.dev"
  exit
end

name = ARGV[0].strip
hostname = ARGV[1].nil? ? ARGV[0] : ARGV[1].strip

# first things first: make sure named conf file doesn't exist already
if File.exists?("#{conf_dir}/#{name}.conf")
  puts "Conf file named #{name}.conf already exists!"
  exit
end

# check to make sure host file exists
if File.exists?(host_dir)
  
  puts "Adding entry to #{host_dir}."
  File.open(host_dir, 'a') do |host_file|
    # append host entry to end of file
    host_file.puts "127.0.0.1\t#{hostname}"
  end
  puts "Host entry added!"
  
  puts "Adding named conf file."
  File.open("#{conf_dir}/#{name}.conf", 'a') do |host_file|
    # add entry
    host_file.puts <<EOF
<VirtualHost *:80>
  ServerName #{hostname}

  DocumentRoot "#{sites_dir}/#{name}"
	DirectoryIndex index.php
	<Directory "#{sites_dir}/#{name}">
		Options FollowSymLinks MultiViews Includes
		AllowOverride All
		Order allow,deny
		Allow from all
	</Directory>
</VirtualHost>
EOF
  end
  puts "Conf entry added!\n"
  
  puts "Restarting apache.\n"
  system "apachectl graceful"
  puts "Done!"
  
end

What you need to do to get this to work:

  1. Change the variables at the top of the file (path to your hosts file, path to the folder where you keep your development site, and path to the directory where you want to keep your named conf files).
  2. Rename the file to add_site(with no extension) and move to your /usr/bin directory.
  3. Chmod the file to be executable.

Now you can run the add_site command and provide it with the name of the site folder and optionally the name of the local domain you'd like to use.

Tagged: rubyscriptapache