2017-07-30 153 views
0

我想缓存我的web应用程序的某个部分。清漆缓存和标题

我有一个端点在http://website.dev/pictures/:id,返回PHP生成的图片。有时候,端点可以使用查询字符串中的宽度和高度来定义图片尺寸:http://website.dev/pictures/:id?w=100&h=100

所以我想缓存这些请求很长一段时间。

我尝试了很简单的VCL,因为我是新来的,而我不想做复杂的事情:

vcl 4.0; 


backend default { 
    .host = "127.0.0.1"; 
    .port = "80"; 
} 

sub vcl_recv { 
    if (req.url ~ "^/api/pictures" && req.method ~ "GET") { 
     # I heard that it was better to unset the cookies here to allow cache 
     unset req.http.cookie; 
     return (hash); 
    } 

    return (pass); 
} 

sub vcl_deliver { 
    if (obj.hits > 0) { 
     set resp.http.X-Cache = "HIT"; 
    } else { 
     set resp.http.X-Cache = "MISS"; 
    } 
} 

但现在,我得到我请求所有MISS。我试图修改才能从我的后端传来的应答有适当的Cache-Control和Expires头:

Response Headers: 
Accept-Ranges:bytes 
Age:0 
Cache-Control:max-age=10000, private 
Connection:keep-alive 
Content-Length:96552 
Content-Type:image/jpeg 
Date:Sun, 30 Jul 2017 16:41:58 GMT 
Expires:Fri, 01 Jan 2100 00:00:00 GMT 
Server:nginx/1.10.3 (Ubuntu) 
Via:1.1 varnish (Varnish/5.1) 
X-Cache:MISS 
X-RateLimit-Limit:60 
X-RateLimit-Remaining:57 
X-Varnish:32772 

Request Headers 
view source 
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 
Accept-Encoding:gzip, deflate 
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,es;q=0.2 
Cache-Control:max-age=0 
Connection:keep-alive 
Cookie:_ga=xxxxxxxxxxxxx 
Host:website.dev:6081 
Upgrade-Insecure-Requests:1 
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 

哪里错了我在这里?我怎样才能确保这些端点上的请求,并且只能长时间被Varnish缓存?

回答

2

预期它不缓存的原因是因为你的Web应用程序发送:

缓存控制:最大年龄= 10000,私人

的内置在VCL逻辑prevents caching in presence of Cache-Control: private

最好的行动当然,这里将解决您的应用程序:要么坚持用公共型使用的Cache-Control或将其删除,只保留Expires头。

如果您不愿意修复该应用程序或者有没有理由,您需要添加一些VCL。下面将确保在“内置VCL逻辑”上面提到的不会阻止缓存中的Cache-Control: private存在:

sub vcl_backend_response { 
    if (beresp.ttl <= 0s || 
     beresp.http.Set-Cookie || 
     beresp.http.Surrogate-control ~ "no-store" || 
     (!beresp.http.Surrogate-Control && 
     beresp.http.Cache-Control ~ "no-cache|no-store") || 
     beresp.http.Vary == "*") { 
     /* 
     * Mark as "Hit-For-Pass" for the next 2 minutes 
     */ 
     set beresp.ttl = 120s; 
     set beresp.uncacheable = true; 
    } 
    return (deliver); 
} 

最后,当你的应用程序在发送正确Expires头缓存,它是由漆忽略因为Cache-Control标题优先于它。 (按照HTTP规范)。记下它,因为它的值将被用作Varnish来缓存对象的持续时间。 (而不是从价值Expires