Introduction
The Python standard library comes pre-installed with a module called http.server, which you can use to create a development server for your project.
The http.server
module gives us an easy way to start a development server for a static directory without modifying a project's source code.
Warning:
http.server
is not recommended for production. It only implements basic security checks.
Starting a development server
First, cd into the root directory of your static website:
cd ./path/to/root/
Then call the python3
command with the --module-name (-m) flag and enter the http.server
module:
python3 -m http.server
Finally, open a web browser and visit http://localhost:8000 or http://127.0.0.1:8000. You should see the index.html
in the root directory or a directory browser for the root directory (if there is no index.html
in the root folder).
Note: Read this post for more information about the difference between the 0.0.0.0
and 127.0.0.1
IP addresses.
Changing the port
That number you see at the end of the localhost URL (8000
) specifies the port. Receiving servers use port numbers to decide which process to forward specific network messages to, and all networked devices have standardised port numbers.
Certain port numbers are reserved for a specific protocol or function. For example, HTTP/HTTPS messages are usually forwarded to port 80 or a port number beginning with 80.
If you'd like to change the port, add the port number you'd like to use to the end of the shell command:
python3 -m http.server 8080
Now you'd visit the same URL with the port number we specified (http://localhost:8080) instead of the default http://localhost:8000
.