闺蜜圈的后台服务使用 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