2014-03-14 51 views

回答

3

通常您不需要设置Expires标题除了Cache-ControlExpires标头告诉缓存(无论它是代理服务器还是浏览器缓存)来缓存文件,直到达到Expires时间。如果定义了Cache-ControlExpires,则优先考虑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头的内容会在一分钟后刷新,但由于最大年龄为600秒,图像撑缓存,直到08:44: 00 GMT。

如果您希望在特定时间内失效,请删除Cache-Control标题并仅使用Expires

马克诺丁汉写了一个非常好的tutorial on caching。考虑到缓存策略时,绝对值得一读。

如果您希望根据Cache-Control: max-age设置Expires标题,则需要在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 

而下面的一块内嵌-C到vcl_deliver功能:

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 
0

假设max-age已经设置好的(您的网络服务器,IE),你可以在您的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; 
    } 
} 

Sou RCE:https://www.g-loaded.eu/2016/11/25/how-to-set-the-expires-header-correctly-in-varnish/

附加信息:

<LocationMatch "/(path1|path2)/"> 
    ExpiresActive On 
    ExpiresDefault "access plus 1 week" 
</LocationMatch> 
:你可以用这个例子你的Apache服务器上设置 max-age