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

Dim*_*duh 10 caching header nginx http-headers

如果只是没有设置,我想通过nginx添加标题(缓存控制).

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

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

Ste*_*ögl 7

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

map $http_cache_control $cachecontrol {
    default   $http_cache_control;
    ""        "public, max-age=31536000";
}
Run Code Online (Sandbox Code Playgroud)

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

proxy_set_header X-Request-ID $cachecontrol;
Run Code Online (Sandbox Code Playgroud)

对于jmcollin92的后续问题,我在SO文档中写了以下内容,现在转录到此处.

X - 请求-ID

nginx的

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

map $http_x_request_id $reqid {                                                 
    default   $http_x_request_id;                                               
    ""        $request_id;                                                      
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将请求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';                              
Run Code Online (Sandbox Code Playgroud)

它也应该传递给后端服务

location @proxy_to_app {
    proxy_set_header X-Request-ID $reqid;
    proxy_pass   http://backend;
    access_log /var/log/nginx/access_trace.log trace;
}
Run Code Online (Sandbox Code Playgroud)