nginx - 仅有时如何在 nginx 中添加 header

标签 nginx cache-control

我有一个到 API 服务器的 nginx 代理。 API 有时会设置缓存控制 header 。如果 API 没有设置缓存控制,我希望 nginx 覆盖它。

我怎么做?

我想我想做这样的事情,但它不起作用。

location /api {
  if ($sent_http_cache_control !~* "max-age=90") {
    add_header Cache-Control no-store;
    add_header Cache-Control no-cache;
    add_header Cache-Control private;
  }
  proxy_pass $apiPath;
}

最佳答案

您不能使用 if在这里,因为 if ,作为重写模块的一部分,在请求处理的早期阶段进行评估,远在 proxy_pass 之前。被调用并从上游服务器返回 header 。

解决问题的一种方法是使用 map指示。用 map 定义的变量仅在使用它们时才进行评估,这正是您在这里所需要的。在这种情况下,您的配置大致如下所示:

# When the $custom_cache_control variable is being addressed
# look up the value of the Cache-Control header held in
# the $upstream_http_cache_control variable
map $upstream_http_cache_control $custom_cache_control {

    # Set the $custom_cache_control variable with the original
    # response header from the upstream server if it consists
    # of at least one character (. is a regular expression)
    "~."          $upstream_http_cache_control;

    # Otherwise set it with this value
    default       "no-store, no-cache, private";
}

server {
    ...
    location /api {
        proxy_pass $apiPath;

        # Prevent sending the original response header to the client
        # in order to avoid unnecessary duplication
        proxy_hide_header Cache-Control;

        # Evaluate and send the right header
        add_header Cache-Control $custom_cache_control;
    }
    ...
}

关于nginx - 仅有时如何在 nginx 中添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31017524/

相关文章:

http - 谷歌浏览器不会在来回时重新验证 etag

Spring HTTP 缓存管理

django - UWSGI套接字更改组并拒绝连接,导致502错误的网关

docker - VM上的Docker NGINX反向代理502错误网关

ruby-on-rails - 使用 Passenger 和 Nginx 将 Rails 应用程序部署到子 URI?

django - 静态 CSS 和图像未在 Django 中加载

php - 我应该在 nginx.conf 中还是使用 Laravel config/cors.php 添加我的 CORS header ?

javascript - Chrome 正在发送缓存控制 :no-cache header

jquery - HTTP 缓存 : Why use ETag instead of Cache-Control and/or Expires?

performance - 用户空间与内核空间程序性能差异