Search code examples
pythontornadovirtualhost

How to create a virtual host for a Tornado HTTP server


I want to redirect a random local domain i.e. http://mypage.local to http://localhost/:8888 where I am running a tornado HTTP server that delivers the website. I got all the information from the official docs here. Code see below (main.py).

I also added the following line to my /etc/vhosts file:

127.0.0.1:8888       mypage.local

But trying to open http://mysite.local results in a classical "Page not found" error. What do I do wrong?

main.py:

from tornado.ioloop import IOLoop
from tornado.web import RequestHandler, Application, url

class MainHandler(RequestHandler):
    def get(self):
        self.write("<p>Hello, world</p><p><a href='/story/5'>Go to story 5</a></p>")

class StoryHandler(RequestHandler):
    def get(self, story_id):
        self.write("this is story %s" % story_id)

def make_app():
    return Application([
        url(r"/", MainHandler),
        url(r"/story/([0-9]+)", StoryHandler)  
    ])

def main():
    app = make_app()
    app.add_handlers(r"mypage.local", [
        (r"/story/([0-9]+)", StoryHandler),
    ])    
    app.listen(8888)
    IOLoop.current().start()


if __name__ == '__main__':
    main()

Solution

  • You should edit /etc/hosts file, but it doesn't support port forwarding. So you can write:

    127.0.0.1       mysite.local
    

    And access your server by http://mysite.local:8888

    You can run tornado on 80 port as root, but it would be better to use nginx to forward requests to tornado:

    server {
      listen 80;
      server_name mysite.local;
    
      location / {
        proxy_pass  http://127.0.0.1:8888;
        include /etc/nginx/proxy.conf;
      }
    }