How to Serve Local Files and Folders with Python Based Web Server ?

If you need to serve a bunch of local static files like html, css, js, images, videos, fonts, etc. over http (in a browser), lying somewhere in one of your filesystem directories, Python’s http.server module can get you up and running quickly instead of installing and setting up (configuring) a more sophisticated web server like Apache or Nginx. Do note that this is only good for local development and testing environments and should never be used for production use cases.

Usage

Make sure you’ve Python 3 installed on your local machine. With that in place all you need to do is this:

$ python -V
Python 3.6.9 # Should be 3.x

$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (<http://0.0.0.0:8000/>) ...

By default the http.server library will spawn up a simple static web server on 0.0.0.0:8000 with the document root defaulting to the current directory, i.e., the current working directory contents will be served. If you visit http://localhost:8000 in your browser you’ll be able to browse through the static content (files and folders).

To configure the document root and host/port to bind on, you can use the following syntax:

# usage: python -m http.server [-h] [--cgi] [--bind ADDRESS] [--directory DIRECTORY] [port]
$ python -m http.server --bind localhost --directory /var/www/html 9090

Note: Since http.server is a mere static file server, it will not execute any file that has code written in languages like Ruby, Python, PHP, JavaScript, etc.

Leave a Reply

Your email address will not be published.