How to set up a local HTTP server?

You can set up a local HTTP server using Python with the following steps:

Using Python 3

  1. Open a terminal.

  2. Navigate to the directory where you want to serve files. For example:

    cd /path/to/your/directory
  3. Start the HTTP server:

    python3 -m http.server 8000

    This command will start a simple HTTP server on port 8000.

  4. Access the server: Open a web browser and go to http://localhost:8000 to see the files in the directory.

Setting Up Basic Authentication (Optional)

If you want to implement basic authentication, you can use the http.server module along with http.server.SimpleHTTPRequestHandler. Here’s a basic example:

  1. Create a file named server.py with the following content:

    from http.server import HTTPServer, SimpleHTTPRequestHandler
    from urllib.parse import urlparse
    import base64
    
    class AuthHandler(SimpleHTTPRequestHandler):
        def do_AUTHHEAD(self):
            self.send_response(401)
            self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"')
            self.send_header('Content-type', 'text/html')
            self.end_headers()
    
        def do_GET(self):
            if self.headers.get('Authorization') is None:
                self.do_AUTHHEAD()
                self.wfile.write(b'Unauthorized')
            else:
                auth = self.headers['Authorization']
                username, password = base64.b64decode(auth.split(' ')[1]).decode().split(':')
                if username == 'your_username' and password == 'your_password':
                    SimpleHTTPRequestHandler.do_GET(self)
                else:
                    self.do_AUTHHEAD()
                    self.wfile.write(b'Unauthorized')
    
    httpd = HTTPServer(('localhost', 8000), AuthHandler)
    httpd.serve_forever()
  2. Run the server:

    python3 server.py
  3. Access the server: Go to http://localhost:8000 in your web browser. You will be prompted for a username and password.

Note

Make sure to replace your_username and your_password with your desired credentials.

This setup allows you to serve files locally and test basic authentication.

0 Comments

no data
Be the first to share your comment!