varnish-4.x VCL之cookie及缓存时间
cookie
varnish对cookie默认不缓存,官方也不建议缓存cookie相关内容
可以强制varnish缓存cookie,官方推荐的cookie操作模块
Add hash_data(req.http.Cookie); in vcl_hash.
• req.http.Cookie header field from clients
• beresp.http.Set-Cookie header field from servers
不缓存cookie有2个主要原因:
1.避免大量相同缓存副本而污染整个缓存
2.避免将基于cookie的缓存副本错误地deliver给了不相干的客户端
strip掉所有Set-Cookie Header相关的内容
if (beresp.ttl > 0s) {
unset beresp.http.Set-cookie;
}
http -p hH http://localhost/cookies.php "Cookie: user=Alice"
GET /cookies.php HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Cookie: user=Alice
Host: localhost
User-Agent: HTTPie/0.9.3
HTTP/1.1 200 OK
Accept-Ranges: bytes
Age: 0
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/plain;charset=UTF-8
Date: Thu, 14 Apr 2016 10:38:54 GMT
Server: nginx/1.8.0
Transfer-Encoding: chunked
Vary: Accept-Encoding
Via: 1.1 varnish-v4
X-Powered-By: PHP/5.6.17
X-Varnish: 262192
x-url: /cookies.php
默认情况下,带Cookie的Age:0,不缓存
缓存时间
示例:
sub vcl_backend_response {
if (beresp.http.cache-control !~ "s-maxage" && bereq.url ~ "\.(html|htm)") {
set beresp.ttl = 10s;
}
if (beresp.http.cache-control !~ "s-maxage" && bereq.url ~ "\.jpg$") {
set beresp.ttl = 10s;
}
if (beresp.status == 503) {
return (retry);
}
}
s-maxage没定义,并且后缀为.jpg的缓存10s