gpt4 book ai didi

django - Gunicorn 不会从 nginx 记录真实 ip

转载 作者:行者123 更新时间:2023-12-04 03:10:51 25 4
gpt4 key购买 nike

我通过 gunicorn、supervisor 和 nginx 作为反向代理运行 django 应用程序,并努力让我的 gunicorn 访问日志显示实际 ip 而不是 127.0.0.1:

日志条目目前看起来像这样:

127.0.0.1 - - [09/Sep/2014:15:46:52] "GET /admin/ HTTP/1.0" ...

supervisord.conf
[program:gunicorn]
command=/opt/middleware/bin/gunicorn --chdir /opt/middleware -c /opt/middleware/gunicorn_conf.py middleware.wsgi:application
stdout_logfile=/var/log/middleware/gunicorn.log

gunicorn_conf.py
#!python
from os import environ
from gevent import monkey
import multiprocessing
monkey.patch_all()

bind = "0.0.0.0:9000"
x_forwarded_for_header = "X-Real-IP"
policy_server = False
worker_class = "socketio.sgunicorn.GeventSocketIOWorker"
accesslog = '-'

我的 nginx 模块配置
server {
listen 80;
root /opt/middleware;
index index.html index.htm;
client_max_body_size 200M;
server_name _;

location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
real_ip_header X-Real-IP;

}
}

我在 location {} block 中尝试了各种组合,但看不出它有什么不同。任何提示表示赞赏。

最佳答案

问题是需要配置 gunicorn 's logging ,因为它(默认情况下)不会显示任何自定义标题。

从文档中,我们发现默认的访问日志格式是由 access_log_format 控制的。并设置为以下内容:

"%(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"

在哪里:
  • h是远程地址
  • l- (未使用)
  • u- (未使用,保留)
  • t是时间戳
  • r是状态行
  • s是请求的状态
  • b是响应长度
  • f是推荐人
  • a是用户代理

  • 您还可以使用以下默认不使用的额外变量对其进行自定义:
  • T - 请求时间(秒)
  • D - 请求时间(以微秒为单位)
  • p - 进程 ID
  • {Header}i - 请求 header (自定义)
  • {Response}o - 响应头(自定义)

  • gunicorn ,所有请求都来自 nginx,因此它将显示为远程 IP。要让它记录任何自定义 header (您从 nginx 发送的内容),您需要调整此参数并添加适当的变量,在您的情况下,您可以将其设置为以下内容:
    %(h)s %(l)s %(u)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s" "%({X-Real-IP}i)s"

    关于django - Gunicorn 不会从 nginx 记录真实 ip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25737589/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com