Josh Stone, Blog

Josh’s projects and security nerdery

Shell Webserver Trick

I like to be efficient about things. Sometimes, I find myself testing a web-based something or other, and I need a web server. But I don’t want to sudo out and start putting things in a system webroot. I don’t want to move what I’m working on into a USERDIR either. I just want a webserver. “Here.”

So this, added to your .bashrc file, will get you a webserver whenever you want it. It will host filesystem content (nothing dynamic, of course) without much fuss:

function webserver () {
    if [ -z "$1" -o -z "$2" ] ; then
        echo "usage: webserver <port> <path>"
    else
        ruby -r webrick \
            -e "s = WEBrick::HTTPServer.new :Port => $1" \
            -e "s.mount '/', WEBrick::HTTPServlet::FileHandler, '$2'" \
            -e "trap('INT') { s.stop }" \
            -e "s.start"
    fi
}

It even has a little bit of self-documenting help if you mess it up. Here’s an example of it working…

Sample run