设置Content-Type头

10

我以前用过这个;

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/gif "now plus 2 weeks"
  // Lots omitted here
</IfModule>

还有这个;

<IfModule mod_headers.c>
  <filesMatch "\\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|JPG)$">
    Header set Cache-Control "max-age=1209600"
  </filesMatch>
  // Lots omitted here
</IfModule>

我可以通过内容类型设置过期时间,并可以通过文件扩展名设置任何标头。

但是这两者似乎都无法让您根据内容类型设置所需的任何标头。

我想根据响应的内容类型设置缓存控制标头 - 请注意,这与文件扩展名不同。 我有“友好的URL”,因此没有要由filesMatch捕获的文件扩展名,但内容类型为text/html

如何针对特定的内容类型设置缓存控制标头?


你的响应中是否存在Cache-Control头? - chris.tian
“如何为特定的内容类型设置缓存控制头?” - 这就是 ExpiresByType 指令所做的事情(确切地说,它设置了 Cache-Control 头的 max-age 指令以及向后兼容性的 Expires 头)。但是,如果您想要在 Cache-Control 头中设置“任何头”或特定指令,则需要使用不同的方法。 - MrWhite
3个回答

9
在2.4版本中,你可以在Header指令中添加expr=,而不是env=。例如:
Header set Cache-Control "max-age=3600" "expr=%{CONTENT_TYPE} == 'text/html'"

在默认模式下(非早期模式),mod_headers 作为输出过滤器运行 - 因此内容类型已经设置并可通过表达式解析器获得。
参考链接:http://httpd.apache.org/docs/2.4/expr.html

谢谢,但我正在使用2.2版本。 - Jake N
Apache 2.4 expression docs 表示 CONTENT_TYPE<If> 中不可用。但我发现这是不准确的,它在 <If> 中是可用的(2.4.52)。 - Jeff
@Jeff,我认为除非你有像“header set early Content-Type”这样的人为情况,否则这不可能是真的。https://pastebin.com/3kP2syS3演示了与手册相匹配的当前行为。在概念层面上:<If>表达式在发生以下所有事件之前进行评估,因此在查询可用的有意义的内容类型之前,应该没有可用的内容类型。
  1. 在请求映射到磁盘之前
  2. 在“type_checker”钩子被调用之前,允许模块猜测内容类型
  3. 在运行“handler”(CGI、代理等)之前,将在处理过程中设置内容类型
- covener

-1

我猜你需要先附加或设置Cache-Control头。请尝试下面的代码片段,不要忘记“no-transform”参数。

<IfModule mod_expires.c>
   ExpiresActive On
   ExpiresByType image/gif "now plus 2 weeks"
  // Lots omitted here

  //This is the magic
  <IfModule mod_headers.c>
     Header append Cache-Control "public, no-transform"
  </IfModule>

</IfModule>

2
我不认为这有任何帮助。Header append Cache-Control "public, no-transform" 是否考虑了内容类型? - Jake N
请注意,在Apache 2.2.12之前,无法使用“Header”指令设置“Cache-Control”头。 - MrWhite

-2
如果您想使缓存内容类型,可以按照以下方式输入:
<IfModule mod_expires.c>

ExpiresActive on

ExpiresByType text/html "access plus 15 days"

</IfModule>

这会设置 ExpiresByType 标头。但这不是我需要的。我需要能够按内容类型设置 Cache-Control - Jake N
1
@JakeN "这将设置ExpiresByType头。" - 我猜你的意思是 Expires 头,ExpiresByType 是 mod_expires 指令。但即使在 Apache 2.0 上,这也应该设置 Cache-Control 头(按 mime-type / Content-Type)。据我所知,你必须回到 Apache 1.3 才能 设置 Expires 头。 - MrWhite

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接