用 nginx+Gunicorn 部署 Flask 应用,调整了 nginx 的配置很多次,重新编译安装 nginx ,也添加了 ngx_http_realip_module ,但是在 Flask 应用里获取到用户 ip 始终是 127.0.0.1.
* 如果前端去掉 nginx+Gunicorn, 直接跑 Flask 自带的 wsgi ,是可以成功获取用户的访问 ip 。
nginx 配置如下:
/usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.8.0
built by gcc 4.8.2 (Ubuntu 4.8.2-19ubuntu1)
configure arguments: --prefix=/usr/local/nginx --with-pcre=/usr/src/pcre-8.36 --with-http_realip_module
nginx.conf
server {
listen 80;
server_name mydomain.com;
location / {
proxy_pass http://127.0.0.1:8000;
# set_real_ip_from 127.0.0.1;
# real_ip_header X-Forwarded-For;
# real_ip_recursive on;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}