Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “Exploring ES6”
Book, exercises, quizzes
(free to read online)
Logo of newsletter “ES.next news”
Newsletter (free)
Cover of book “JavaScript for impatient programmers”
Book (free online)

SimpleHTTPServer: a quick way to serve a directory

[2014-06-23] dev, webdev
(Ad, please don’t block)

Python’s SimpleHTTPServer is the classic quick solution for serving the files in a directory via HTTP (often, you’ll access them locally, via localhost). This is useful, because there are some things that don’t work with file: URLs in web browsers.

Using SimpleHTTPServer  

SimpleHTTPServer is invoked like this (the parameter <port> is optional):

python -m SimpleHTTPServer <port>

(On OS X, Python is pre-installed and this command works out of the box.)

Let’s look at an example of using SimpleHTTPServer: During the following Unix shell interaction, I first list the files in the current directory and then start SimpleHTTPServer to serve it.

$ ls .
$ python -m SimpleHTTPServer
Serving HTTP on port 8000 ...

Afterwards, I can access the following URLs:

  • http://localhost:8000/ lists the files in the current directory (namely, just foo.html). If there were a file index.html, it would be displayed, instead.
  • http://localhost:8000/foo.html displays the file foo.html in the current directory.

Customizing SimpleHTTPServer  

The following Unix shell script demonstrates how to customize SimpleHTTPServer so that it serves files that have a given file name extension with a given media type. One case where that matters is Firefox being picky about the media type of the webapp.manifest.


import SimpleHTTPServer
import SocketServer

PORT = 8000

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    '.webapp': 'application/x-web-app-manifest+json',

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "Serving at port", PORT