Simple HTTP Server using Python

problem

You want to quickly spin off a web server on your local machine and serve files via HTTP.

SOLUTION

Python has you covered. You can check the version by opening your terminal and running the following command:

				
					python -V
				
			

If the above fails, you can try:

				
					python3 -V
				
			

In order to start an HTTP web server, you first need to change to the directory you wish to serve its files. For example:

				
					cd Desktop
				
			

Or go to the parent folder:

				
					cd ..
				
			
running

In order to start serving files, fire up the HTTP server:

				
					python3 -m http.server
				
			

Or if you have earlier version, e.g. 2.x:

				
					python -m SimpleHTTPServer
				
			

By default, the files are served at localhost and port 8000.

If started successfully, you can access your files by browsing to localhost.

output
Python http server running example

To change the port, you can pass it as an argument at the command. For example to serve at port 9000:

				
					python3 -m http.server 9000
				
			
output
Python http server with changed port number

You can also specify the directory instead of cd-ing to it. For example to serve directory /Users at port 9001:

				
					python3 -m http.server -d /Users 9001
				
			
output
Python http server example running in custom directory and port

conclusion

In web design/ development it’s very useful to know how to quickly and easily start a web server for variety of reasons like testing your web applications, etc.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x