Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python Flask使用Nginx做代理时如何获取真实IP

$
0
0

使用 Flask 开发的项目,但部署到线上 Docker 容器中后,因为使用了 Nginx 做代理,所以 Flask 无法获取真实 IP 地址,获取到的都是 192.0.0.1 ,解决方法如下:

首先是 Nginx 的配置,需要在 转发的请求headers中设置好真实IP :

location /path { root html; proxy_pass http://127.0.0.1:5000/; proxy_set_header X-Real-IP $remote_addr; }

然后在 Flask 中 通过headers获取IP ,为了兼容使用 nginx 不使用 nginx 的情况,做了一些处理:

ip = request.remote_addr try: _ip = request.headers["X-Real-IP"] if _ip is not None: ip = _ip except Exception as e: print(e)

通过上述代码,就可以获取到真实 IP 了。

转载请注明出处 : http://www.zgljl2012.com/2017/01/08/python-flaskshi-yong-nginxzuo-dai-li-shi-ru-he-huo-qu-zhen-shi-ip/

Viewing all articles
Browse latest Browse all 9596

Trending Articles