首先,nginx必定会设置一个Header传送过来真实的IP

nginx.conf

server {

  proxy_set_header X-Real-IP $remote_addr;
location / {
proxy_pass http://192.168.7.206:8888/;
}
}

然后,tornado的Handler里面进行如下处理:

class Handler(BaseRequestHandler):

    def post(self):
self.get() def get(self):
remote_ip = self.request.headers.get("X-Real-Ip", "")

此处,下面两行其实是没有任何区别的,ng的header到了tornado会做一次统一整理(具体可以参考class HTTPHeaders)。

ip = self.request.headers.get("X-Real-Ip", "")
ip = self.request.headers.get("X-Real-IP", "")

然后,就可以了。


但是,这里为啥还有但是呢?这段日志还有奇怪的地方,它记录的还不对,这个是tornado的默认日志。

[I 150806 14:54:21 web:1811] 200 POST / (192.168.7.62) 2.74ms

看tornado==v4.2.0的代码web.py文件某处一定有如下类似的部分:

    def log_request(self, handler):
"""Writes a completed HTTP request to the logs. By default writes to the python root logger. To change
this behavior either subclass Application and override this method,
or pass a function in the application settings dictionary as
``log_function``.
"""
if "log_function" in self.settings:
self.settings["log_function"](handler)
return
if handler.get_status() < 400:
log_method = access_log.info
elif handler.get_status() < 500:
log_method = access_log.warning
else:
log_method = access_log.error
request_time = 1000.0 * handler.request.request_time()
log_method("%d %s %.2fms", handler.get_status(),
handler._request_summary(), request_time)

这块其实就是日志的实现,_request_summary 又是啥?

    def _request_summary(self):
return "%s %s (%s)" % (self.request.method, self.request.uri,
self.request.remote_ip)

后续继续看,发现,self.request.remote_ip这个其实就是tornado针对客户端IP做的快捷访问,这里为啥不对呢?

原来要在初始化listen的时候设置一个参数:

def main():
app = Application()
app.listen(options.port, xheaders = True)

产生的效果就是

[I 150806 13:52:53 web:1908] 200 POST / (192.168.7.214) 1.86ms

真实IP反映到Tornado的基础日志里了。

具体实现追踪可以查看 tornado\httpserver.py 中的相关代码。

class _ServerRequestAdapter(httputil.HTTPMessageDelegate):

    def headers_received(self, start_line, headers):
if self.server.xheaders:
self.connection.context._apply_xheaders(headers) class _HTTPRequestContext(object): def _apply_xheaders(self, headers):
"""Rewrite the ``remote_ip`` and ``protocol`` fields."""
# Squid uses X-Forwarded-For, others use X-Real-Ip
ip = headers.get("X-Forwarded-For", self.remote_ip)
ip = ip.split(',')[-1].strip()
ip = headers.get("X-Real-Ip", ip)
if netutil.is_valid_ip(ip):
self.remote_ip = ip
# AWS uses X-Forwarded-Proto
proto_header = headers.get(
"X-Scheme", headers.get("X-Forwarded-Proto",
self.protocol))
if proto_header in ("http", "https"):
self.protocol = proto_header def _unapply_xheaders(self):
"""Undo changes from `_apply_xheaders`. Xheaders are per-request so they should not leak to the next
request on the same connection.
"""
self.remote_ip = self._orig_remote_ip
self.protocol = self._orig_protocol

tornado 反向代理后 获取真实客户端IP的更多相关文章

  1. nginx设置反向代理,获取真实客户端ip

    upstream这个模块提供一个简单方法来实现在轮询和客户端IP之间的后端服务器负荷平衡. upstream abc.com { server 127.0.0.1:8080; server 127.0 ...

  2. nginx经过多层代理后获取真实来源ip

    nginx取 $remote_addr 当做真实ip,而事实上,$http_X_Forwarded_For 才是用户真实ip,$remote_addr只是代理上一层的地址 解决方案: 在 http 模 ...

  3. JAVA获取客户端请求的当前网络ip地址(附:Nginx反向代理后获取客户端请求的真实IP)

    1. JAVA获取客户端请求的当前网络ip地址: /** * 获取客户端请求的当前网络ip * @param request * @return */ public static String get ...

  4. NGINX前端代理TOMCAT取真实客户端IP

    nginx前端代理tomcat取真实客户端IP 使用Nginx作为反向代理时,Tomcat的日志记录的客户端IP就不在是真实的客户端IP,而是Nginx代理的IP.要解决这个问题可以在Nginx配置一 ...

  5. nginx+tomcat集群配置(3)---获取真实客户端IP

    前言: 在初步构建的nginx+tomcat服务集群时, 发现webserver获取到的客户端ip都是同一个, 皆为作为反向代理服务的nginx所在的机器IP. 这不太符合我们的基本需求, 为将来的数 ...

  6. ABP vNext 审计日志获取真实客户端IP

    背景 在使用ABP vNext时,当需要记录审计日志时,我们按照https://docs.abp.io/zh-Hans/abp/latest/Audit-Logging配置即可开箱即用,然而在实际生产 ...

  7. 关于nginx反向代理后获取不到客户端的真实ip地址问题

    前段时间在我的网站上用nginx做了一下反向代理,最近发现不能获取客户端ip了,都是拿到的127.0.0.1的本地ip... 通过查资料后,再去看了看我的配置文件,结果发现我没有如下配置: nginx ...

  8. nginx做反向负载均衡,后端服务器获取真实客户端ip(转)

    首先,在前端nginx上需要做如下配置: location / proxy_set_hearder host                $host; proxy_set_header X-forw ...

  9. nginx反向代理如何获取真实IP?

    由于客户端和web服务器之间增加了中间层,因此web服务器无法直接拿到客户端的ip,通过$remote_addr变量拿到的将是反向代理服务器的ip地址. 1.安装--with-http_realip_ ...

随机推荐

  1. python 自学 1 day

    #!/usr/bin/env python #coding = utf-8 age_of_oldby = 56 user = "fyt" word = "fyt" ...

  2. python 输出十六进制中文乱码

    代码中红色字体为解决方案: #-*-coding:utf-8-* import csv filename='C:\Users\yaru\Desktop\Senti_Value(1).csv' data ...

  3. java中常见的几种Runtimeexception

    转自http://blog.csdn.net/qq635785620/article/details/7781026 一般面试中java Exception(runtimeException )是必会 ...

  4. c#网络编程

    c#网络编程 1.system.net命名空间 DNS类:DNS类包含了许多的方法,总结起来常用的就是获取获取主机地址,获取主机名,根据地址 获取DNS主机信息,根据主机名获取DNS信息: IPadd ...

  5. JavaScript设计模式:读书笔记(未完)

    该篇随我读书的进度持续更新阅读书目:<JavaScript设计模式> 2016/3/30 2016/3/31 2016/4/8 2016/3/30: 模式是一种可复用的解决方案,可用于解决 ...

  6. WinZip Registry Optimizer 初体验

    WinZip Registry Optimizer是来自著名压缩软件WinZip开发团队的一种可以修复.组织和整理Windows注册表的应用程序,它可以删除无效的注册表条目,整理碎片从而提升系统性能, ...

  7. java 枚举类型 构造函数及用法

    // 1. 定义枚举类型 public enum Light { // 利用构造函数传参 RED (1), GREEN (3), YELLOW (2); // 定义私有变量 private int n ...

  8. install google chrome

    32bit: wget https://dl.google.com/linux/direct/google-chrome-stable_current_i386.deb sudo dpkg -i go ...

  9. Tomcat Start 报错 (COULD NOT DELETE MAY BE LOCKED BY ANOTHER PROCESS)

    jsp文件重命名后发布不起来了,提示文件被占用,原因是当前的java ee项目 与它引用的java项目 依赖了相同的jar包,删除了clean 再发布,问题解决,如有需要再引用回来 http://it ...

  10. 获取贴图及IES文件

    最近看了一下以前写的关于收集贴图的函数...又完善了一下,老链接:http://www.cnblogs.com/3dxy/p/3988751.html fn saveusedmaps spath se ...