Sometime we need to run a quick static webserver which can serve various files in a directory. This can be pretty handy to serve html and js content from a web server for html/javascript development and debugging purpose. This will work if no server side rendering is required. We are using Mac for the purpose of this tutorial, but it should work on Linux and windows also.
Here are quick steps to run a web server on command line:
$ mkdir mywebdir $ cd mywebdir $ echo "Hello world..." > hello.txt $ echo "Hello world2..." > hello2.txt $ python -m SimpleHTTPServer Serving HTTP on 0.0.0.0 port 8000 ...
If you visit http://localhost:8000/ then you will see this page:
You can also visit http://localhost:8000/hello.txt and see the following page:
You should also see the following log entries in shell:
1.0.0.127.in-addr.arpa - - [26/Sep/2015 21:31:13] "GET / HTTP/1.1" 200 - 1.0.0.127.in-addr.arpa - - [26/Sep/2015 21:31:22] "GET /hello.txt HTTP/1.1" 200 -
Changing default port
To change the port to a custom port (say 5678) run the following:
$ python -m SimpleHTTPServer 5678 Serving HTTP on 0.0.0.0 port 5678
Looking into the code
In case you want to find the file location of the code for module SimpleHTTPServer, you can run the following:
$ python -c "import SimpleHTTPServer; print SimpleHTTPServer.__file__"
The above outcome for a mac machine. That mean module code can be viewed in following file:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SimpleHTTPServer.py