【问题标题】:Nginx, how to add header if it is not setNginx,如果未设置,如何添加标头
【发布时间】:2012-11-15 00:44:23
【问题描述】:

我想在 nginx 中添加一个标头(Cache-control),除非它没有设置。

在某些情况下,我需要通过 nginx 中的标头来增加缓存时间。

【问题讨论】:

  • 对我来说同样的问题,这个问题没有任何有价值的答案。如果尚未设置,我想添加带有 uuid 的 X-correlationId 标头。有可能吗?

标签: caching header nginx http-headers


【解决方案1】:

您可以使用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;
}

【讨论】:

  • 地图不能在另一个块内使用。在子配置文件中渲染它无用
猜你喜欢
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
  • 2015-06-10
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 2021-05-06
相关资源
最近更新 更多