在apache中有条件地设置缓存头

发布于 2024-12-10 12:09:12 字数 406 浏览 1 评论 0原文

我想根据访问文件的路径有条件地设置缓存标头。基本上,访问 http://www.example.com/cache/$cache_key/* 应该提供具有遥远未来缓存标头的文件。

我使用重写规则来设置环境变量,然后尝试根据该变量设置缓存控制标头。然而,变量似乎在过程中设置得太晚了;条件标头规则永远不会被执行。

RewriteRule ^cache/.*?/(.*) /$1 [env=asset:true,L]
Header set Cache-control "max-age=30"
Header set Cache-Control "max-age=31536000" env=asset
Header unset ETag env=asset

有更好的方法吗?我尝试了几种目录和位置块的组合,但没有成功。

I want to conditionally set cache headers depending on what path files are accessed from. Basically, accessing http://www.example.com/cache/$cache_key/* should serve files with far in the future cache headers.

I'm using a rewrite rule to set an environment variable and then attempting to set cache control headers based on that variable. However, it seems like the variable is being set too late in the process or something; the conditional header rules are never getting executed.

RewriteRule ^cache/.*?/(.*) /$1 [env=asset:true,L]
Header set Cache-control "max-age=30"
Header set Cache-Control "max-age=31536000" env=asset
Header unset ETag env=asset

Is there a better way to do this? I've tried a couple of combinations of Directory and Location blocks with no success.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晨曦慕雪 2024-12-17 12:09:12

使用 phpinfo() 我确定环境变量最终在重写的请求中根本没有被设置,所以问题不在于请求的顺序,而在于它似乎将变量扔掉了。使用查询字符串而不是 URL 并且重写似乎是我能够实现此功能的唯一方法。我确实同意,似乎应该有更好的方法。

RewriteCond %{QUERY_STRING} longcache=true(&|$)
RewriteRule .* - [ENV=LONGCACHE:true,L]

Header set Cache-Control "max-age=30" env=!LONGCACHE
Header set Cache-Control "max-age=31536000" env=LONGCACHE

睁开眼睛获得更多不同的答案:

重定向后,您的 asset 环境变量将重命名为 REDIRECT_asset,因此您的条件标头指令需要为:

Header set Cache-Control "max-age=31536000" env=REDIRECT_asset

Using phpinfo() I determined the environment variable ends up not being set at all on the rewritten request, so the problem isn't the order of the request, it's that it seems to toss the variable out. Using the query string instead of the URL and not rewriting seemed to be the only way I could get this working. I do agree, it seems like there should be a better way.

RewriteCond %{QUERY_STRING} longcache=true(&|$)
RewriteRule .* - [ENV=LONGCACHE:true,L]

Header set Cache-Control "max-age=30" env=!LONGCACHE
Header set Cache-Control "max-age=31536000" env=LONGCACHE

MORE DIFFERENT ANSWER OBTAINED BY OPENING EYES:

Your asset environment variable gets renamed to REDIRECT_asset after the redirect, so your conditional Header directive needs to be:

Header set Cache-Control "max-age=31536000" env=REDIRECT_asset
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文