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

时间:2015-03-16 08:52:35

标签: python tornado virtualhost

我想将一个随机的本地域,即http://mypage.local重定向到http://localhost/:8888,我正在运行提供该网站的龙卷风HTTP服务器。我从官方文档here获得了所有信息。代码见下文(main.py)。

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

127.0.0.1:8888       mypage.local

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

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

2 个答案:

答案 0 :(得分:3)

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

127.0.0.1       mysite.local

http://mysite.local:8888

访问您的服务器

您可以在80端口上以root身份运行tornado,但最好使用nginx将请求转发给龙卷风:

server {
  listen 80;
  server_name mysite.local;

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

答案 1 :(得分:2)

来自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),
    ]),
])