Deprecated: Serve a local directory via HTTP/HTTPS with Python3 http.server

Originally posted on 2020-10-27

Update on 2022-02-03: NOTE - If you want to serve media files a local NodeJS server is a better choice.

Need to serve a local directory via HTTP from a web server?

python3 -m http.server

Need to serve a local directory via HTTP from a web server on a specific port?

python3 -m http.server PORT

Want to start an HTTPS Python web server? First, generate a self-signed cert:

openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365

Then run this script. You'll likely need to type the password when the server starts.

#!/usr/bin/env python3

from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl


httpd = HTTPServer(('0.0.0.0', 4443), BaseHTTPRequestHandler)

httpd.socket = ssl.wrap_socket (httpd.socket,
        keyfile="key.pem",
        certfile='cert.pem', server_side=True)

httpd.serve_forever()