Gunicorn nginx 反代获取真实 ip 地址

闺蜜圈的后台服务使用 gunicorn 运行,对外接口通过 nginx 进行反代。但是反代有个问题,那就是 gunicorn 获取到的服务器的 ip 地址都是 127.0.0.1。

作为一个强迫症能忍受这个?那自然不行啊。

在 nginx 配置文件中增加 proxy_set_header

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

修改 gunicorn 启动参数,修改日志格式为:

--access-logformat='%({X-Real-IP}i)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"'

重启 nginx 以及 gunicorn 服务,就可以记录真实 ip 地址了:

参数说明:

h is the remote address
l is - (not used)
u is - (not used, reserved)
t is the time stamp
r is the status line
s is the status of the request
b is length of response
f is referrer
a is user agent
You can also customize it with the following extra variables that are not used by default:

T - request time (in seconds)
D - request time (in microseconds)
p - the process id
{Header}i - request header (custom)
{Response}o - response header (custom)

 

参考链接:https://stackoverflow.com/questions/25737589/gunicorn-doesnt-log-real-ip-from-nginx

☆版权☆

* 网站名称:obaby@mars
* 网址:https://nai.dog/
* 个性:https://oba.by/
* 本文标题: 《Gunicorn nginx 反代获取真实 ip 地址》
* 本文链接:https://nai.dog/2024/07/17578
* 短链接:https://oba.by/?p=17578
* 转载文章请标明文章来源,原文标题以及原文链接。请遵从 《署名-非商业性使用-相同方式共享 2.5 中国大陆 (CC BY-NC-SA 2.5 CN) 》许可协议。


You may also like

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注