The one-line web server

Every now and again, I run into a situation where a bunch of HTML files can’t be opened by simply double-clicking the index.html, and need to be hosted on a web server to behave properly. I think this used to happen with WebWorks output, and built Jekyll output does this. It’s also sometimes handy to have a web server spinning in the background so you can modify and preview things on the fly.

In the past when this came up, I’d fall down a wormhole about installing the Apache or IIS web server, or trying to figure out where Apple moved the built-in out-of-date Apache web server in the latest version of macOS. (I think it’s gone completely in Catalina.) But instead of sifting through the many different Apache installers and Medium articles about how to get an entire full stack going, I realized this is dead simple if you have Python installed.

First, do you have Python installed? A quick python -V will tell you. If you don’t, grab a copy.

Open a command line in the directory you want to serve up, and if you have Python 3, do this:

python3 -m http.server

If you’re a Windows user, that is probably python and not python3.

If you’re still using Python 2, do this instead:

python -m SimpleHTTPServer

Now point a web browser at localhost:8000 and there’s your stuff.

If you’ve already got something on port 8000, put another port number after the command, like python3 -m http.server 90125.

Don’t expect to run your Fortune 500’s production environment on this. It’s great for testing, though.

(Thanks: https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server and https://docs.python.org/3/library/http.server.html)