如何为 Tornado HTTP 服务器创建虚拟主机

How to create a virtual host for a Tornado HTTP server

我想重定向一个随机本地域,即 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。代码见下(main.py).

我还在 /etc/vhosts 文件中添加了以下行:

127.0.0.1:8888       mypage.local

但是尝试打开 http://mysite.local 会导致典型的 "Page not found" 错误。我做错了什么?

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()

您应该编辑 /etc/hosts 文件,但它不支持端口转发。所以你可以这样写:

127.0.0.1       mysite.local

并通过http://mysite.local:8888

访问您的服务器

你可以运行 tornado 在80 端口作为root,但是最好使用nginx 将请求转发给tornado:

server {
  listen 80;
  server_name mysite.local;

  location / {
    proxy_pass  http://127.0.0.1:8888;
    include /etc/nginx/proxy.conf;
  }
}

来自Tornado documentation

application = web.Application([
    (HostMatches("example.com"), [
        (r"/", MainPageHandler),
        (r"/feed", FeedHandler),
    ]),
])

可以这样用

application = web.Application([
    (HostMatches("localhost"), [
        (r"/", Admin_Handler)
    ]),

    (HostMatches("website1.com"), [
        (r"/", Site_1_Handler),
        (r"/feed", Site_1_FeedHandler),
    ]),

    (HostMatches("website2.com"), [
        (r"/", Site_2_Handler),
        (r"/feed", Site_2_FeedHandler),
    ]),

    (HostMatches("(.*)"), [
        (r"/", Main_Handler),
        (r"/feed", Main_FeedHandler),
    ]),
])