来自上游服务器的 nginx 监控响应

Bri*_*ian 7 reverse-proxy nginx openresty

我有一个使用 nginx 的反向代理设置。

Client ------> Nginx ------------------------------------> Backend Server
       <------       <-----------------------------------
                      (I want to see the requests here)
Run Code Online (Sandbox Code Playgroud)

如何将包括从后端服务器发送到 nginx 的标头在内的 http 请求记录到文件中?

也许nginx http 代理模块中的指令之一可以帮助我做到这一点。

但我找不到任何有用的指令。

Ale*_*rov 5

注意:我在 OP 添加标签之前给出了这个答案openresty。我不是 Openresty 的专家,但我确信我在香草 Nginx 的情况下提供了正确的详细信息。


“后端服务器”在 Nginx 术语中称为“上游”。文档中有一个单独的页面,列出了与上游相关的变量。其中,你可能会感兴趣

  • $upstream_addr – 处理请求的后端服务器的 IP 地址
  • $upstream_connect_time, $upstream_header_time, $upstream_response_time– Nginx 等待连接接受的时间、来自上游的标头以及后端处理请求所需的时间
  • $upstream_http_*NAME*将包含响应头*NAME*。例如,$upstream_http_etag$upstream_http_last_modified
  • 还有其他变量可以报告缓存状态、重试等。

将这些记录到 Nginx 日志文件中是很常见的做法。您需要声明自己的日志格式,例如:

log_format my_upstream '$remote_addr [$time_local] "$request" $status'
  '"$upstream_addr" $upstream_response_time $upstream_http_etag';
Run Code Online (Sandbox Code Playgroud)

然后在locationor 中使用它server

access_log /var/log/nginx/upstream.log my_upstream;
Run Code Online (Sandbox Code Playgroud)

  • 奇怪的是我的 `upstream_*` 值总是显示 `-`。例如 `upstream_addr`、`upstream_http_host` 和 `upstream_connect_time` (2认同)