Setting up a local web server with Python

Cover Image

Setting up a Local Web Server with Python (It's Easier Than You Think!)

Hey everyone! Ever wanted to quickly test out some HTML, CSS, or JavaScript without uploading it to a "real" server? Or maybe you're just curious about how web servers work behind the scenes? Well, I've got good news: you can set up a simple web server on your own computer using Python, and it's surprisingly easy!

Python comes with a built-in module called http.server that makes this process a breeze. Let's dive in!

Step-by-Step Guide

  1. Make sure you have Python installed. Most Linux distributions come with Python pre-installed. You can check by opening your terminal and typing: python3 --version. If it shows a version number, you're good to go! If not, you'll need to install Python (your distribution's package manager can help with that).
  2. Navigate to your project directory. This is the folder containing the files you want to serve (like your HTML, CSS, and JavaScript files). Use the cd command in your terminal to get there. For example: cd /home/yourusername/my_website
  3. Start the server! This is the magic command. In your terminal, type: python3 -m http.server. This will start a web server listening on port 8000 by default.
  4. Access your website. Open your web browser and go to http://localhost:8000. You should see the contents of your project directory displayed in the browser. Click on your HTML file to view your website.

Customizing the Port

Want to run your web server on a different port? You can specify it after the command. For example, to run the server on port 8080, use: python3 -m http.server 8080. Then access your website at http://localhost:8080.

Serving Specific Files

By default, http.server will list the contents of the current directory if there's no index.html file. If you want to serve a specific file as the default page, you can use a small trick. Create an index.html file that simply redirects to your desired file. For example:


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0; url=my_page.html">
</head>
<body>
</body>
</html>

This index.html will automatically redirect to my_page.html when you visit http://localhost:8000.

Stopping the Server

When you're done, just press Ctrl+C in your terminal to stop the server.

That's it!

See? Setting up a local web server with Python is incredibly easy! This is a fantastic way to quickly test your web development projects or share files on your local network. Happy coding!