Nginx,如果没有设置,如何添加标头

时间:2012-11-27 11:42:49

标签: caching header nginx http-headers

如果只是没有设置,我想通过nginx添加标题(Cache-control)。

在某些情况下我需要增加缓存时间(使用php),并通过标题“说”nginx。

对不起,如果不清楚,我真的是个新手)

1 个答案:

答案 0 :(得分:5)

您可以使用map填充变量$cachecontrol。如果$http_cache_control(来自客户端的标头)为空,请设置自定义值。否则(默认)重用客户端的值。

map $http_cache_control $cachecontrol {
    default   $http_cache_control;
    ""        "public, max-age=31536000";
}

之后您可以使用该变量发送上游标头。

proxy_set_header X-Request-ID $cachecontrol;

对于来自jmcollin92的后续问题,我在SO文档中写了以下内容,现在转录到这里。

X - 请求-ID

nginx的

反向代理可以检测客户端是否提供X-Request-ID标头,并将其传递给后端服务器。如果没有提供这样的头,它可以提供随机值。

map $http_x_request_id $reqid {                                                 
    default   $http_x_request_id;                                               
    ""        $request_id;                                                      
}

上面的代码将请求ID存储在变量$reqid中,随后可以在日志中使用它。

log_format trace '$remote_addr - $remote_user [$time_local] "$request" '        
                 '$status $body_bytes_sent "$http_referer" "$http_user_agent" ' 
                 '"$http_x_forwarded_for" $reqid';                              

它也应该传递给后端服务

location @proxy_to_app {
    proxy_set_header X-Request-ID $reqid;
    proxy_pass   http://backend;
    access_log /var/log/nginx/access_trace.log trace;
}
相关问题