根据 nginx 中的 mime 类型有条件地添加过期标头

Sil*_*oon 9 nginx

在 ubuntu 12.10 上运行 nginx 1.4.1

需要根据 http 响应的 MIME 类型/内容类型有条件地发送过期标头。

在 location / { 中添加了这段简单的代码

if ($sent_http_content_type = "text/css") { 
expires 7d;
}
Run Code Online (Sandbox Code Playgroud)

即使 $sent_http_content_type 包含“text/css”,也不会发送 expires 标头

如何解决这个问题?

检查文件扩展名是不够的,因为在我的应用程序 js、css 中,图像是从 php 动态生成的。所以需要检查 mime 并添加基于它的标题。

小智 16

从 nginx 1.7.9 开始:

map $sent_http_content_type $expires {
  default         off;
  application/pdf 42d;
  ~image/         max;
}

expires $expires;
Run Code Online (Sandbox Code Playgroud)

注意:$sent_http_content_type 是有效的,但在服务器处理完请求之前无法访问它...

答案指向application/pdf允许日期值的地图条目,或者甚至可以application/pdf modified +42d是例如


小智 8

ifNginx 中的指令在重写阶段的早期处理,因此该$sent_http_content_type变量尚未初始化 -有关详细信息,请参阅此 nginx 错误报告

编辑比较用户名,实际上,该错误报告很可能就是您!(^_^)

同样,该expires指令似乎不像例如那样支持变量add_header。因此,由于您无法根据文件扩展名静态指定位置,因此我只能想到两种基本方法。

其中之一是使用mapadd_header由瓦迪姆建议的方法上面的手动设置HTTP头,而不是让expires指令去做。这相当不灵活,因为它不会设置Expires标题,但我希望现在任何浏览器都能Cache-Control通过设置来做正确的事情。这是我简单测试过的示例:

map $sent_http_content_type $cacheable_types {
    "text/css"    "max-age=864000";
    "image/jpeg"  "max-age=864000";
    default       "";
}

# ...

server {
    # ...
    location / {
        # ...
        add_header "Cache-Control" $cacheable_types;
    }
}
Run Code Online (Sandbox Code Playgroud)

864000是以秒为单位的 10 天 - 您必须将其更改为您想要的任何内容。这种方法的好处是,你可以为每个文件类型指定不同的时间,甚至覆盖等方面的Cache-Control头-你这头的讨论在这里,和官方的部分从HTTP RFC在这里,如果你喜欢的东西更正式。

第二种方法是只安排将导致可缓存内容的请求都位于特定路径下,您可以在这样的location指令中使用该路径:

location / {
    # ...
    location /static {
        expires 10d;
    }
}
Run Code Online (Sandbox Code Playgroud)

这使得 nginx 配置更容易,因为您可以使用其内置expires指令,但它是否是一个选项在很大程度上取决于您是否可以在代码中强制执行该 URL 模式。


Vad*_*dim 3

$sent_http_content_type 无效。请求标头值可以通过 $http_ name访问。另外,对于 Content-type 标头,nginx 嵌入了变量 $content_type。

如果你想检查 $content_type 与一堆类型,最好使用 map:

   map $content_type $test_header {
        "text/css"  OK;
        "text/html" OK;
        ...
        default "";
   }

   server {
        location / {
             add_header "X-Test" $test_header;
        }
   }
Run Code Online (Sandbox Code Playgroud)

如果 $test_header 计算结果为空字符串,则不会设置 header。

有关更多信息,请参阅: http://nginx.org/en/docs/http/ngx_http_core_module.html#variables http://nginx.org/en/docs/http/ngx_http_map_module.html http://nginx.org/ zh/docs/http/ngx_http_headers_module.html#add_header