nginx读取自定义响应头

时间:2015-11-09 16:18:01

标签: nginx

我尝试从自定义标头中记录数据。作为回应:

Cache-Control:no-cache
Connection:keep-alive
Content-Type:application/json
Date:Mon, 09 Nov 2015 16:09:09 GMT
Server:nginx/1.9.4
Transfer-Encoding:chunked
X-Extended-Info:{"c":70}
X-Powered-By:PHP/5.6.12

在php脚本(Symfony2)中:

$response->headers->set('X-Extended-Info', json_encode($info))

我想写一些来自" X-Extended-Info"。

的日志数据

Nginx配置:

log_format main_log '$extended_info';
server {
    set $extended_info '-';
    if ($sent_http_x_extended_info != '') {
        set $extended_info $sent_http_x_extended_info;
    }
   ...
}

在日志中我只看到' - '。 我看了nginx - read custom header from upstream server,但这个解决方案在我的情况下不起作用(我尝试使用$ upstream_http_,$ http _)。

可以从phpfpm读取响应吗? 谢谢。

2 个答案:

答案 0 :(得分:1)

if指令在您的请求发送到后端之前有效,因此当时没有$sent_http_...变量。

您可以使用map指令。

log_format main_log '$extended_info';

map $sent_http_x_extended_info $extended_info {
    default $sent_http_x_extended_info;
    "" "-";
}

答案 1 :(得分:0)

我遇到了与Niomin相同的问题,其中预期的标题只是显示为“-”。我可以将我的fastcgi_pass指令更改为一个upstream值,然后才将其硬编码为unix套接字,如下所示:

#fastcgi_pass unix:/home/phillip/php.sock; fastcgi_pass php_backend;

我认为为upstream服务器创建一个条目是记录凉爽的$upstream_http_*响应头所必需的...下面是我为替换硬编码的unix套接字而创建的...... / p>

upstream php_backend { server unix:/home/phillip/php.sock; }

然后我编辑了log_format以包括其中的upstream_http_x_forwarded_by

log_format main '$host - $remote_addr - [$time_local] "$request" ' '$status "X-Powered-By $upstream_http_x_powered_by "$http_referer" ''"$http_user_agent"';