使用Apache为文件系统中不存在的路径添加到期标头

Ben*_*odd 6 apache mod-rewrite cdn mod-expires mod-headers

出于CDN失效的目的,我需要在站点URL的路径元素中添加前缀.每当发布新版本的资产时,都会更改此信息.

然后使用mod_rewrite将URL重写为:http://example.com/cdn/20111030/images/image.jpghttp://example.com/images/image.jpg,这是资产实际所在的位置.

我想在响应中添加长期到期标题(至少3个月)(对于文件系统中实际不存在的第一个URL).有谁知道如何做到这一点?

And*_*ndy 5

看来,如果您在Apache配置中为自己的解决方案添加RewriteEngine/Rule,则可以正确选取Location并在/ cdn调用上提供Expires/Cache-Control,并且不为非cdn调用提供它们,一个小变化:

    # in apache config
    RewriteEngine On
    RewriteRule ^/cdn/[^/]*/(.*) /$1 [L]

    <Location "/cdn">
      Header unset ETag
      FileETag None
      ExpiresActive on
      ExpiresDefault "access plus 1 year"
    </Location>

我无法在Apache配置中看到这个问题.


mik*_*wn2 4

来自http://drupal.org/node/974350#comment-5305368
这些规则适用于 480 周,但您可以相应地调整时间。

<IfModule mod_rewrite.c>
  RewriteEngine on
  <IfModule mod_headers.c>
    # Transform /cdn/***/ to /
    RewriteCond %{REQUEST_URI} ^/cdn/([0-9a-zA-Z])*/(.+)$
    RewriteRule .* /%2 [L,E=CDN:1]
    # Apache will change CDN to REDIRECT_CDN.

    # Set a far future Cache-Control header (480 weeks), which prevents
    # intermediate caches from transforming the data and allows any
    # intermediate cache to cache it, since it's marked as a public resource.
    Header set Cache-Control "max-age=290304000, no-transform, public" env=REDIRECT_CDN

    # Set a far future Expires header. The maximum UNIX timestamp is somewhere
    # in 2038. Set it to a date in 2037, just to be safe.
    Header set Expires "Tue, 20 Jan 2037 04:20:42 GMT" env=REDIRECT_CDN

    # Pretend the file was last modified a long time ago in the past, this will
    # prevent browsers that don't support Cache-Control nor Expires headers to
    # still request a new version too soon (these browsers calculate a
    # heuristic to determine when to request a new version, based on the last
    # time the resource has been modified).
    # Also see http://code.google.com/speed/page-speed/docs/caching.html.
    Header set Last-Modified "Wed, 20 Jan 1988 04:20:42 GMT" env=REDIRECT_CDN

    # Do not use etags for cache validation.
    Header unset ETag env=REDIRECT_CDN
  </IfModule>
</IfModule>
Run Code Online (Sandbox Code Playgroud)

另请参阅AdvAgg 规则,因为这些处理未安装 mod_headers 或 mod_expires 的服务器。它使用 FilesMatch 指令;advagg 文件有一个相当独特的文件名,因此我可以这样做。AdvAgg 后备在这种情况下不起作用,因为mod_expires不能使用环境变量;FileETag也不能。据我所知,mod_headers是在 apache 中设置遥远未来时间的理想方法。