vcl 4.0; #声明为varnish4.0
import directors; #调用多个后端主机做集群#
probe health_check { #定义健康状态检测机制#
.url = "/.health_check.html"; #定义检测文件#
.window = 5; #定义一共检测几次#
.threshold = 3; #定义检测几次失败则认为后端主机失效#
.interval = 2s; #每隔2秒检测一次#
.timeout = 3s; #连接超时时长为3秒#
}
backend dynamic { #定义后端动态主机#
.host = "192.168.11.178";
.port = "80";
.probe = health_check;
}
backend static { #定义前端主机#
.host = "192.168.11.177";
.port = "80";
.probe = health_check;
}
sub vcl_recv {
# Happens before we check if we have this in cache already.
#
# Typically you clean up the request here, removing cookies you don't need,
# rewriting the request, etc.
if (req.url ~ "(?i).*php.*") { #当访问的url包括php,则转到动态服务器,否则所有请求转到静态服务器,实现动静分离#
set req.backend_hint = dynamic;
} else {
set req.backend_hint = static;
}
if (req.url ~ "(?i)(register|login)$") { #如果请求地址结尾为register或者login,注册和登录页面,则不查缓存,,直接从后端服务器获取内容#
return (pass);
}
}
sub vcl_backend_response {
# Happens after we have read the response headers from the backend.
#
# Here you clean the response headers, removing silly Set-Cookie headers
# and other mistakes your backend does.
#当后端服务器回复给varnish的响应如果不包含公共缓存信息,而且请求为jpg等静态资源,则卸载cookie信息并缓存资源1小时#
if (beresp.http.cache-control !~ "s-maxage") {
if (bereq.url ~ "(?i)\.(jpg|jpeg|png|gif|css|js|xml)$") {
unset beresp.http.Set-Cookie;
set beresp.ttl = 3600s;
}
}
#当varnish请求后端服务器的url包括php,则卸载cookie信息并缓存资源1小时#
if (bereq.url ~ "(?i).*php.*") {
unset beresp.http.Set-Cookie;
set beresp.ttl = 3600s;
}
}
sub vcl_deliver {
# Happens when we have all the pieces we need, and are about to send the
# response to the client.
#
# You can do accounting or modifying the final object here.
if (obj.hits>0) {
set resp.http.X-Cache = "HIT via "+server.ip;
} else {
set resp.http.X-Cache = "MISS via "+server.ip;
}
}