Nginx代理时在gunicorn的日志中记录真实访问IP

一、问题概述

在通过Nginx负载均衡的情况下,gunicorn的log中记录的访问访问日志并不是用户的IP,而是Nginx主机的IP。

二、解决方法

1. Nginx配置:

其中proxy_set_header X-Real-IP $remote_addr;在请求头中加入了真实的用户IP信息,并一起发送给了后端的gunicorn 服务。

	location /api {
	    proxy_pass http://zy_ems;
		proxy_set_header Host $host;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	}

2. gunicorn配置

在gunicorn的启动配置文件中添加下面一段配置:

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

前面的内容为其他的信息,最后的"%({X-Real-IP}i)s"是在日志中加入用户真实的访问IP。
具体关于日志格式的定制可参考:
1. gunicorn官网(logging)
2.Gunicorn doesn’t log real ip from nginx
官方文档

三、实现效果

上面两条日志为访问配置前,日志的内容只有nginx的ip,最后一条日志为配置后,除了有nginx的ip之外,追加了用户的ip信息。
在这里插入图片描述

  
Email : [email protected]
Website : http://beyonderwei.com
  
WeChat:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章