2

请帮助我在清漆配置中添加过期标头。max_age 已在 vcl_fetch 中定义,需要根据 max_age 添加 expires header。

4

2 回答 2

3

通常你不需要设置Expires标题除了Cache-Control. 标Expires头告诉缓存(无论是代理服务器还是浏览器缓存)在Expires到达时间之前缓存文件。如果同时定义了 和 ,Cache-Control则优先。ExpiresCache-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标题,内容应在一分钟后刷新,但由于 max-age 设置为 600 秒,因此图像会一直缓存到格林威治标准时间 08:44:00。

如果您希望在特定时间使内容过期,则应删除Cache-Control标题并仅使用Expires.

Mark Nottingham 写了一篇关于缓存的非常好的教程。在考虑缓存策略时绝对值得一读。

如果您希望Expires基于 设置标头Cache-Control: max-age,则需要在 VCL 中使用 inline-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
于 2014-03-14T11:40:28.953 回答
0

假设max-age已经设置(即通过您的网络服务器),您可以在 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/

附加信息:您可以max-age使用此示例在您的 apache 服务器上进行设置:

<LocationMatch "/(path1|path2)/">
    ExpiresActive On
    ExpiresDefault "access plus 1 week"
</LocationMatch>
于 2017-09-11T10:32:15.887 回答