最近写的项目因为要记录用户ip来实现访问频次控制以及访问限制等功能,但是在使用
request.remote_addr
来获取用户ip时,却发现获取到的一直是
127.0.0.1
这就给我整懵了,在百度后发现,因为使用了Nginx做代理,所以Flask无法获取真实IP地址
解决办法如下:
1、首先是Nginx的配置, 需要在转发的请求headers中设置好真实IP:
#PROXY-START/
location /
{
expires 12h;
if ($request_uri ~* "(php|jsp|cgi|asp|aspx)")
{
expires 0;
}
proxy_pass http://127.0.0.1:端口号;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;#用户真实ip
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#用户代理ip
proxy_set_header REMOTE-HOST $remote_addr;
#持久化连接相关配置
#proxy_connect_timeout 30s;
#proxy_read_timeout 86400s;
#proxy_send_timeout 30s;
#proxy_http_version 1.1;
#proxy_set_header Upgrade $http_upgrade;
#proxy_set_header Connection "upgrade";
add_header X-Cache $upstream_cache_status;
#Set Nginx Cache
add_header Cache-Control no-cache;
}
#PROXY-END/
2、然后在Flask中通过headers获取IP:
ip = request.headers.get('X-Real-IP')
3、如果用户使用了代理, 获取的IP是代理后的IP,就需要获取上层IP。 通过X-Forwarded-For获取IP的链路(结果是一个数组), IP以逗号隔开:
ip = request.headers.get('X-Forwarded-For')
4、改完Nginx配置记得重启 可以写一个下面的方法来获取用户IP
def get_user_ip(request):
if request.headers.get('X-Forwarded-For'):
return request.headers['X-Forwarded-For']
elif request.headers.get('X-Real-IP'):
return request.headers.get('X-Real-IP')
else:
return request.remote_addr
最后修改于2020年4月2日 22:51
©允许规范转载
Flask Python版权声明:如无特殊说明,文章均为本站原创,转载请注明出处
本文链接:https://www.yangyingqi.com/28.html