首先,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. linux压缩解压文件

    首先进入文件夹 cd /home/ftp2/1520/web 压缩方法一:压缩web下的888.com网站 zip -r 888.com.zip888.com 压缩方法二:将当前目录下的所有文件和文件 ...

  2. 关于URI URL URN

    刚琢磨.整理了关于escape.encodeURIComponent.encodeURI的知识.突然又对URI有点模糊了,遂整理了以下资源 : 资源一: URL,URI 和URN 的举例理解 资源二: ...

  3. iOS纯代码适配masonry中mas_的问题

    //equalto 和 mas_equalto 是有区别的.但是我们不打算去了解,可以通过添加以下代码来统一. //注意!! 宏定义必须要放在 import 引入头文件之前! //define thi ...

  4. YII2的增删改查

    insert into table (field1,field2)values('1','2');delete from table where   condition update  table s ...

  5. 使用sublime遇到的问题汇总

    问题一:用GBK编码的文件用Sublime打开出现中文乱码的解决办法: 通过ctrl+shift+p--package control install安装插件"ConvertToUTF8&q ...

  6. Psam_ISO7816

    ISO7816协议1-4部分下载

  7. pyqt4:连接的一个带有参数的方法

    一般在pyqt4中的信号连接很少连接带参数的方法,很多时候连接带参数的方法节约不少代码量. self.s5_thread=scene.Worker5() self.log_get=QtCore.QTi ...

  8. Docker学习---ubuntu环境

    添加Docker的ATP仓库 sudo sh -c "echo deb https://get.docker.io/ubuntu docker main > /etc/apt/sour ...

  9. org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection 原因

    org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection 可能出现的原因     ...

  10. python字符串基础知识

    1.python字符串可以用"aaa",'aaa',"""aaa""这三种方式来表示 2.python中的转义字符串为" ...