使用nginx代理后,获取用户真实ip

使用nginx代理后,获取用户真实ip

使用nginx转发请求时,应用中获取到的用户ip 都是127.0.0.1,获取真实ip必须重写一些头部才行。通常在WSGI环境中经常使用的变量:REMOTE_ADDR ,在nginx转发时设置头部携带这个变量

nginx设置

server {
    listen 80;
    server_name _;
    location / {
    	..................
        proxy_pass         http://127.0.0.1:8000/;
        # $host 变量,Host 为变量名 
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;						
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        
    }
}

改完niginx 配置记得重启

之后可以在获取请求时取出对应的request头部信息,或者使用ProxyFix修复工具
ProxyFix是werkzeug.contrib.fixers模块下的一个WSGI 中间件,作用是修复代理后无法直接获取
用户ip和请求主机的问题
官方文档
This middleware can be applied to add HTTP proxy support to an
application that was not designed with HTTP proxies in mind. It
sets REMOTE_ADDR, HTTP_HOST from X-Forwarded headers. While
Werkzeug-based applications already can use
:py:func:werkzeug.wsgi.get_host to retrieve the current host even if
behind proxy setups, this middleware can be used for applications which
access the WSGI environment directly。
If you have more than one proxy server in front of your app, set
num_proxies accordingly.
Do not use this middleware in non-proxy setups for security reasons.
The original values of REMOTE_ADDR and HTTP_HOST are stored in
the WSGI environment as werkzeug.proxy_fix.orig_remote_addr and
werkzeug.proxy_fix.orig_http_host
:param app: the WSGI application
:param num_proxies: the number of proxy servers in front of the app.

可以看到这个中间件还可以接收一个num_proxies参数用以指定之前经过多少代理,默认为1

from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)

配置完成之后就可以获取用户真实ip了

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值