通過網上搜索並實踐發現:使用self.request.remote_ip可以獲取到客戶端的IP
但是如果我們使用了代理後發現獲取到的IP是127.0.0.1或是服務器端IP,難道使用了代理就獲取不到客戶端IP?其實不是的,因爲我們還需要通過進行如下設置:
Tornado支持通過 x-real-ip 或 x-forwarded-for來獲取IP,但前提是需要在你的HTTPServer實例中增加xheaders=True參數
# To get remote_ip, it should set xheaders=True when initializing HTTPServer
http_server = HTTPServer(Application(), xheaders=True)
# 或者如下
# application.listen(8080, xheaders=True)
nginx配置x-forwarded-for時只需在反向代理規則中增加一行:proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
參考鏈接:
1. http://www.au92.com/archives/tornado-get-remote-ip-address.html
2. http://www.au92.com/archives/tornado-get-remote-ip-address-complement.html