http - 使用 nginx 真正记录 POST 请求正文(而不是 "-")

标签 http post logging nginx webserver

我正在尝试记录 POST 主体,并将 $request_body 添加到 http 子句中的 log_format,但是 access_log 在我发送 POST 请求后,命令仅打印“-”作为正文:

curl -d name=xxxx myip/my_location

我的 log_format(在 http 子句中):

log_format client '$remote_addr - $remote_user $request_time $upstream_response_time '
                  '[$time_local] "$request" $status $body_bytes_sent $request_body "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

我的位置定义(在服务器子句中):

location = /c.gif {  
  empty_gif;  
  access_log logs/uaa_access.log client;  
}

如何从 curl 打印实际的 POST 数据?

最佳答案

Nginx 除非确实需要,否则不会解析客户端请求主体,因此它通常不会填充 $request_body 变量。

异常(exception)情况是:

  • 它将请求发送给代理,
  • 或 fastcgi 服务器。

因此,您确实需要将 proxy_passfastcgi_pass 指令添加到您的 block 中。

最简单的方法是将其作为代理服务器发送到 Nginx 本身,例如使用以下配置:

location = /c.gif {  
    access_log logs/uaa_access.log client;
    # add the proper port or IP address if Nginx is not on 127.0.0.1:80
    proxy_pass http://127.0.0.1/post_gif; 
}
location = /post_gif {
    # turn off logging here to avoid double logging
    access_log off;
    empty_gif;  
}

如果您只希望收到一些 key 对值,那么限制请求正文大小可能是个好主意:

client_max_body_size 1k;
client_body_buffer_size 1k;
client_body_in_single_buffer on;

我在使用 empty_gif; 和 curl 进行测试时也收到了“405 Not Allowed”错误(在浏览器中没问题),我将其切换为 return 200; 到使用 curl 进行正确测试。

关于http - 使用 nginx 真正记录 POST 请求正文(而不是 "-"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17609472/

相关文章:

python - 转换简单的Python请求将POST转换为Rust reqwest

java - 在 Spring applicationContext.xml 中使用 P6Spy 和数据源

spring-boot - 使用 Logback MDC 进行 Spring Boot ErrorController 日志记录

apache - 如何在 Apache 中查看 HTTP 响应消息

rest - 无法理解如何将帖子发送到 Lingvo API

wordpress - 网站链接的重定向/安全问题

php - 使用 PHP 后台任务获取 HTTP 1.1 错误 400

javascript - 我们可以仅使用 javascript 访问发布/获取数据吗?

c# - 为什么我的 HTTP POST 正文内容被接收/处理为 NULL?

java - Log4j 日志在错误的文件中滚动(在当天之前,跳过周末)