用nginx真正记录POST请求体(而不是“ - ”)

时间:2013-07-12 07:15:20

标签: http post logging nginx webserver

我正在尝试记录POST正文,并将$request_body添加到log_format子句中的http,但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数据?

1 个答案:

答案 0 :(得分:52)

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

例外情况是:

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

所以你真的需要将proxy_passfastcgi_pass指令添加到你的块中。

最简单的方法是将其作为代理服务器发送给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;  
}

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

client_max_body_size 1k;
client_body_buffer_size 1k;
client_body_in_single_buffer on;

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