Mrli
别装作很努力,
因为结局不会陪你演戏。
Contacts:
QQ博客园

flask+nginx如何获得真实IP

2019/09/15 flask nginx
Word count: 190 | Reading time: 1min

如果是通过 flask 的 request.remote_addr获取的 ip 都是 127.0.0.1

解决方案:

nginx.conf中添加

1
2
3
# proxy_set_header Host $host:80; 
# proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {
listen 8888;
server_name 0.0.0.0;
charset utf-8;
client_max_body_size 75M;
location /static{
alias /home/apollo3d/Documents/Cl/webenv/.../static;
}

location / {
include uwsgi_params;
uwsgi_pass 127.0.0.1:8889;
uwsgi_param UWSGI_SCRIPT app:app; # 启动flask的文件:Flask的实例
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

Python代码

1
2
3
4
if request.headers.getlist("X-Forwarded-For"):
ip = request.headers.getlist("X-Forwarded-For")[0]
else:
ip = request.remote_addr

查自:V2EX

拓展:

X-Forwarded-For 可能会有多个 IP ,如果浏览器使用了代理的话
正确的做法应该是抓 X-Real-IP,或者分隔 X-Forwarded-For取第 1 个值

Author: Mrli

Link: https://nymrli.top/2019/03/02/flask-nginx如何获得真实IP/

Copyright: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.

< PreviousPost
ACM_线性筛
NextPost >
构造一个能发数据的POST请求头
CATALOG
  1. 1. 解决方案:
    1. 1.1. nginx.conf中添加
    2. 1.2. Python代码
  2. 2. 拓展: