Thoughts of an Eaten Sun

through the mind of kyle tolle

Simple HTTP Servers

Want to serve up your current directory via HTTP? This is very helpful if you’re working on code on your laptop, but would like to test how it looks on your phone. The following commands will allow you to do just that.

Once you’ve run one of them, through your machine’s browser, you’ll be able to hit localhost:8000 and see the index.html rendered!

Python

cd /path/you/want/served
python -m SimpleHTTPServer

Source

PHP

cd /path/you/want/served
php -S localhost:8000

Source

Ruby

cd /path/you/want/served
ruby -run -e httpd . -p 8000

Source

Node.js

cd /path/you/want/served
http-server -p 8000

Thanks @mappingkat for the idea!

Source


The Python command seems the easiest to remember. The PHP command is nice to run some simple scripts locally. And the Ruby command is nice to have, since I am a Rubyist after all.

Wanted to make it even easier to run the Ruby command? Easy! Add an alias to your shell. I use zsh, so I’ve added the following line to my .zshrc:

alias http="ruby -run -e httpd . -p 8000"

Now, all I have to do is type http and the simple HTTP server is ready to go!


Update: I’ve already run into the issue where I’d like to run the http alias from two directories at the same time. Since it has the 8000 port hard-coded, using it a second time doesn’t work. But, thanks again to the StackOverflow link above, I was able to replace my alias with a function.

function http {
  port="${1:-8000}"
  ruby -run -e httpd . -p $port
}

Now I can serve up one folder using http and the other using http 8001 and have access to both at the same time.