在基于烧瓶的应用程序中获取客户端IP

问题描述 投票:0回答:1

我在服务器中部署了Flask应用程序。我们正在使用Nginx。 nginx设置如下:

proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_read_timeout 25s;
proxy_pass http://127.0.0.1:8000;
add_header X-Cache $upstream_cache_status;

在Flask设置中,我完成了以下操作:

app = Flask(__name__, static_folder=None)
app.wsgi_app = ProxyFix(app.wsgi_app)

现在,每当用户访问网站时,我都想要一个真正的IP。目前我正在接受

127.0.0.1

我尝试过如下:

if request.headers.getlist("X-Forwarded-For"):
    ip = request.environ['HTTP_X_FORWARDED_FOR']
else:
    ip = request.remote_addr

请问有人在这里指导我。

nginx flask clientip
1个回答
0
投票

使用request.access_route

https://github.com/pallets/werkzeug/blob/master/werkzeug/wrappers.py

@cached_property
def access_route(self):
    """If a forwarded header exists this is a list of all ip addresses
    from the client ip to the last proxy server.
    """
    if 'HTTP_X_FORWARDED_FOR' in self.environ:
        addr = self.environ['HTTP_X_FORWARDED_FOR'].split(',')
        return self.list_storage_class([x.strip() for x in addr])
    elif 'REMOTE_ADDR' in self.environ:
        return self.list_storage_class([self.environ['REMOTE_ADDR']])
    return self.list_storage_class()

示例Nginx配置:

location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Protocol https;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_redirect off;
        proxy_pass http://127.0.0.1:9000;
}
© www.soinside.com 2019 - 2024. All rights reserved.