Using Python's simple HTTP server

I started programming in PHP, so by default I would use apache even when I just wanted to test basic HTML files. As I was learning Python, I discovered a great HTTP request handler. I often need to build a quick demo in JavaScript and HTML and Python's SimpleHTTPServer has come in quite handy.

1

You will want to invoke the HTTP server from the directory you consider to be the document root. Supposing your project folder is /home/tyler/project1 you can change directories like this:

cd /home/tyler/project1

If your project is in your home directory you could also use this command:

cd ~/project1
2

You can invoke the simple HTTP server with the -m flag like this:

python -m SimpleHTTPServer

This will automatically use your current directory as the document root. It will server files in the current directory and below. It directly maps the HTTP requests to the directory structure.

When you start the server you should see something like this:

Serving HTTP on 0.0.0.0 port 8000 ...

By default, this command will start the HTTP server on port 8000 and bind to any available IP (signified by 0.0.0.0). In most cases, you'll be able to make requests to http://localhost:8000 in order to use the server.

3

If you want to use a port other than 8000, you can do so by specifying the port at the end of the same command:

python -m SimpleHTTPServer 8080

Keep in mind that if you specify a port lower than 1024 (like port 80), you will have to use root:

sudo python -m SimpleHTTPServer 80
4

You can visit your site in a web browser by typing the following in the url bar:

http://localhost:8000