请帮助我在varnish配置中添加expires头。vcl_fetch中已经定义了max_age,需要根据max_age添加expires头部。
发布于 2014-03-14 19:40:29
通常,除了Cache-Control之外,您不需要设置Expires header。Expires标头告诉缓存(代理服务器或浏览器缓存)在到达Expires时间之前缓存文件。如果同时定义了Cache-Control和Expires,则Cache-Control优先。
考虑以下响应头:
HTTP/1.1 200 OK
Content-Type: image/jpeg
Date: Fri, 14 Mar 2014 08:34:00 GMT
Expires: Fri, 14 Mar 2014 08:35:00 GMT
Cache-Control: public, max-age=600根据Expires header,内容应该在一分钟后刷新,但由于最大年龄设置为600秒,图像将一直缓存到格林威治时间08:44:00。
如果您希望在特定时间使内容过期,则应该删除Cache-Control标头,并且只使用Expires。
Mark Nottingham写了一个非常好的tutorial on caching。在考虑缓存策略时,它绝对值得一读。
如果你想设置基于Cache-Control: max-age的内联头部,你需要在你的VCL中使用Expires -C。以下代码是从https://www.varnish-cache.org/trac/wiki/VCLExampleSetExpires复制的,以备将来删除该页面时使用。
添加以下原型:
C{
#include <string.h>
#include <stdlib.h>
void TIM_format(double t, char *p);
double TIM_real(void);
}C以及vcl_deliver函数的以下内联-C代码:
C{
char *cache = VRT_GetHdr(sp, HDR_RESP, "\016cache-control:");
char date[40];
int max_age = -1;
int want_equals = 0;
if(cache) {
while(*cache != '\0') {
if (want_equals && *cache == '=') {
cache++;
max_age = strtoul(cache, 0, 0);
break;
}
if (*cache == 'm' && !memcmp(cache, "max-age", 7)) {
cache += 7;
want_equals = 1;
continue;
}
cache++;
}
if (max_age != -1) {
TIM_format(TIM_real() + max_age, date);
VRT_SetHdr(sp, HDR_RESP, "\010Expires:", date, vrt_magic_string_end);
}
}
}C发布于 2017-09-11 18:32:16
假设已经设置了max-age (即由您的set服务器设置),您可以在vcl中使用此配置设置Expires头:
# Add required lib to use durations
import std;
sub vcl_backend_response {
# If max-age is setted, add a custom header to delegate calculation to vcl_deliver
if (beresp.ttl > 0s) {
set beresp.http.x-obj-ttl = beresp.ttl + "s";
}
}
sub vcl_deliver {
# Calculate duration and set Expires header
if (resp.http.x-obj-ttl) {
set resp.http.Expires = "" + (now + std.duration(resp.http.x-obj-ttl, 3600s));
unset resp.http.x-obj-ttl;
}
}来源:https://www.g-loaded.eu/2016/11/25/how-to-set-the-expires-header-correctly-in-varnish/
附加信息:您可以使用以下示例在您的apache服务器上设置max-age:
<LocationMatch "/(path1|path2)/">
ExpiresActive On
ExpiresDefault "access plus 1 week"
</LocationMatch>https://stackoverflow.com/questions/22393701
复制相似问题