Nice web server script to serve any directory using WEBrick

At present, I am doing some web development in the form of a rich Javascript client. Now I have a need to serve up pages locally, but I don’t want to run a heavy web server just for that. So I wrote a little Ruby script to allow me to start a WEBrick server in any directory on the fly, which is great for testing content locally.

Here it is:

require 'rubygems'
require 'webrick'
require 'optparse'
options = {}

# Parse options
optparse = do|opts|
    opts.banner = "Usage: websrv.rb [options]"

	options[:port] = 3000
	opts.on( '-p', '--port PORT', 'Port Number (default 3000)' ) do |port|
	     options[:port] = port
	options[:docroot] = Dir.pwd
	opts.on( '-d', '--doc_root PATH', 'Document Root (default current dir)' ) do |docroot|
		puts docroot
	     options[:docroot] = docroot
	options[:bind] = "localhost"
	opts.on( '-b', '--bind HOST', 'Address to bind to (default localhost)' ) do |bind|
	     options[:bind] = bind
	opts.on( '-h', '--help', 'Display this screen' ) do
	  puts opts


# Initialize and start WEBrick'rhtml', 'text/html')
server =
	:BindAddress => options[:bind], 
	:Port => options[:port], 
	:DocumentRoot => options[:docroot] )
trap "INT" do server.shutdown end

I just make this script executable and copy it to /usr/bin/websrv. Then I navigate to my directoy of choice (or use the -d parameter to specify a specific directory for the document root) and issue ‘websrv’. Nice.

The great part about being able to bind to a specific address, is that I can serve up the content to other machines on the network (e.g. my VM running Windows over bridged networking, thereby allowing me to test pages from Internet Explorer).

Update (2011.07.18): I added a line before instantiating the server to process .rhtml files, which causes the server to process ERB tags, which allows me to add some server-side logic to mimic the server on which I will eventually deploy the content. Works like a bomb (but without the KABOOM!).

Tags: ,

  • Jesse House


    worked great!

  • admin

    Glad you found it useful. I added a line to be able to process ERB in documents with a .rhtml extension, which also turned out quite useful for me.