使用 nginx 真正记录 POST 请求正文(而不是“-") [英] Really logging the POST request body (instead of "-") with nginx

查看:47
本文介绍了使用 nginx 真正记录 POST 请求正文(而不是“-")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试记录 POST 正文,并将 $request_body 添加到 http 子句中的 log_format,但是 access_log 命令只是在我使用以下命令发送 POST 请求后打印-"作为正文:

I'm trying to log POST body, and add $request_body to the log_format in http clause, but the access_log command just prints "-" as the body after I send POST request using:

curl -d name=xxxx myip/my_location

我的日志格式(在 http 子句中):

My log_format (in http clause):

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"';

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

My location definition(in server clause):

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

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

How can I print the actual POST data from curl?

推荐答案

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

Nginx doesn't parse the client request body unless it really needs to, so it usually does not fill the $request_body variable.

例外情况是:

  • 它将请求发送到代理,
  • 或 fastcgi 服务器.

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

So you really need to either add the proxy_pass or fastcgi_pass directives to your block.

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

The easiest way is to send it to Nginx itself as a proxied server, for example with this configuration:

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;  
}

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

If you only expect to receive some key-pair values, it might be a good idea to limit the request body size:

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 正确测试.

I also received "405 Not Allowed" errors when testing using empty_gif; and curl (it was ok from the browser), I switched it to return 200; to properly test with curl.

这篇关于使用 nginx 真正记录 POST 请求正文(而不是“-")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆