#定义后端服务器
backend web1 {
.host="192.168.0.20";
.port="80";
}
backend web2 {
.host="192.168.0.30";
.port="80";
}
#只允许本机使用purgers请求方法清除缓存
acl purgers {
"127.0.0.1";
"172.16.0.0"/16;
}
sub vcl_recv {
if(req.request=="PURGE"){
if(!client.ip~purgers) {
error 405 "Mothod not allow";
}
}
#静态资源交给web1服务器
if(req.url ~ "\.(html|htm|shtml|css|js|jpg|png|gif|jpeg)"){
set req.backend=web1;
}
#php页面交给web2服务器,并跳过缓存
if(req.url ~ "\.php") {
set req.backend=web2;
return(pass);
}
return(lookup);
}
#将命中的缓存清除
sub vcl_hit {
if (req.request == "PURGE") {
purge;
error 200 "Purged OK";
}
}
#如果请求清除的资源不在缓存列表中,返回404状态
sub vcl_miss {
if (req.request == "PURGE") {
purge;
error 404 "Not in cache";
}
}
#如果请求清除的资源是一个不可缓存的资源,返回502状态
sub vcl_pass {
if (req.request == "PURGE") {
error 502 "Purged on a passed object.";
}
}
#缓存对象存活时间
sub vcl_fetch {
if(req.url ~ "\.(html|htm|shtml|css|js|jpg|png|gif|jpeg)"){
set beresp.ttl=7200s;
}
}
#将结果返回给客户端并在响应头部添加两字段,显示命中与否,并显示后端响应的web服务器
sub vcl_deliver {
if(obj.hits > 0) {
set resp.http.X-Cache="HIT from" + " " + server.ip;
}else{
set resp.http.X-Cache="MISS";
}
set resp.http.Backend-IP=req.backend;
}