使用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了

你可能感兴趣的:(Flask)