The python -m http.server command is a built-in module in Python that provides a simple HTTP server for serving files from a directory. It's especially useful for quick development and testing.
- Purpose: Start a basic HTTP server to serve files from the current directory.
- Available in: Python 3.x (Python 2.x uses
SimpleHTTPServerinstead).
To start a simple HTTP server using Python, navigate to the directory you want to serve and run:
python -m http.server [port]port(optional): The port number on which the server will listen. Defaults to8000if not specified.
-
Navigate to the desired directory:
cd /path/to/your/directory -
Start the server:
python -m http.server 8000
This starts an HTTP server on port
8000. The server will serve files from/path/to/your/directory. -
Access the server:
Open a web browser and go to
http://localhost:8000. You will see the directory listing of files available in the directory.
-
--directory: Specify a different directory to serve.python -m http.server --directory /path/to/another/directory 8000
-
--bind: Bind to a specific network interface (e.g.,0.0.0.0to listen on all interfaces).python -m http.server --bind 0.0.0.0 8000
-
--cgi: Enable support for CGI scripts. (Requires setting up the CGI directory.)python -m http.server --cgi 8000
- Not Suitable for Production: This server is intended for development and testing purposes. It does not provide robust security features, and should not be used as a production server.
- Directory Exposure: The server will serve any file in the specified directory, including hidden files.
-
Custom Port and Host:
python -m http.server 8080 --bind 192.168.1.10
This binds the server to IP
192.168.1.10and uses port8080. -
Running in Background:
You can run the server in the background using
nohup:nohup python -m http.server 8000 &
-
Port Already in Use: If you encounter an error about the port already being in use, try using a different port or stopping the process using the port.
lsof -i :8000
Then kill the process:
kill -9 <PID>
The python -m http.server command is a quick and easy way to serve files from a directory for development and testing. While it’s not suited for production environments, it’s very useful for quickly sharing files or testing web applications locally.