Question

I am writing an rather simple http web server in python3. The web server needs to be simple - only basic reading from config files, etc. I am using only standard libraries and for now it works rather ok.

There is only one requirement for this project, which I can't implement on my own - virtual hosts. I need to have at least two virtual hosts, defined in config files. The problem is, that I can't find a way how can I implement them in python. Does anyone have any guides, articles, maybe some simple implementation how can this be done?

I would be grateful for any help.

Was it helpful?

Solution

For a simple HTTP web server, you can start with the WSGI reference implementation:

wsgiref is a reference implementation of the WSGI specification that can be used to add WSGI support to a web server or framework. It provides utilities for manipulating WSGI environment variables and response headers, base classes for implementing WSGI servers, a demo HTTP server that serves WSGI applications,...

Modifying the example server to check the HTTP_HOST header, here is a simple app that responds, depending on the virtual host, with a different text. (Extending the example to use a configuration file is left as an exercise).

import wsgiref
from wsgiref.simple_server import make_server

def my_app(environ,start_response):
    from io import StringIO
    stdout = StringIO()
    host = environ["HTTP_HOST"].split(":")[0]
    if host == "127.0.0.1":
        print("This is virtual host 1", file=stdout)
    elif host == "localhost":
        print("This is virtual host 2", file=stdout)
    else:
        print("Unknown virtual host", file=stdout)

    print("Hello world!", file=stdout)
    print(file=stdout)
    start_response(b"200 OK", [(b'Content-Type',b'text/plain; charset=utf-8')])
    return [stdout.getvalue().encode("utf-8")]

def test1():
    httpd = make_server('', 8000, my_app)
    print("Serving HTTP on port 8000...")

    # Respond to requests until process is killed
    httpd.serve_forever()

OTHER TIPS

Virtual hosts work by obeying the Host: header in the HTTP request.

Just read the headers of the request, and take action based on the value of the Host: header

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top