# 导入directors模块实现负载均衡;并定义acl,来控制purger(更新缓存)的使用
# --------------------------------------------
.host = "192.168.159.129";
.probe = { # 此外定义健康状态检查还可以这样定义
# ++++++++++++++++++++++++++ 手动调整backend server健康状态 +++++++++++++++++++++++++
# help backend.set_health
# backend.set_health <backend_pattern> ``[auto|healthy|sick]``
# Set health status on the backends.
# 例如: backend.set_health server2 sick
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# --------------------------------------------
new websrvs =directors.random(); # 当调度算法为random时才会有权重
srvs.add_backend(server1,1); # backend 'server1' with weight '1'
srvs.add_backend(server2,2); # backend 'server2' with weight '2'
# --------------------------------------------
set req.backend_hint=websrvs.backend();
# set req.backend_hint=srvs.backend(req.http.cookie);
# 正则匹配 login或admin隐私信息不允许服务端缓存
if (req.url ~ "(?i)^/(login|admin)") {
# url重写,告诉后端服务器真实的请求者,安全避免重复添加,还可定义在记录日志中
if (req.http.X-Fowarded-For) {
set req.http.X-Forwarded-For = req.http.X-Forwarded-For + "," + client.ip;
set req.http.X-Forwarded-For = client.ip;
# purge的使用:更新一个缓存,而更新一组缓存用ban
if (req.method == "PURGE"){
if (!client.ip ~ purgers) {
return(synth(405,"Purging not allowed for "+client.ip));
if (req.url ~ "(?i)\.(jpg|jpeg|png)$") {
set req.backend_hint = server2;
set req.backend_hint = server1;
# ++++++++++++++++++++++++++++++++ 后端有多个虚拟主机 ++++++++++++++++++++++++++++++++
# if (req.http.host ~ "foo.com" || req.http.host == "www.foo.com") {
# set req.backend_hint = foo;
# } elsif (req.http.host ~ "bar.com") {
# set req.backend_hint = bar;
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# --------------------------------------------
sub vcl_backend_response {
# 客户端的图片类信息可以除去cookies标志让服务器能够缓存,并定义缓存有效期为2H
if (bereq.url ~ "(?i)\.(jpg|jpeg|png|gif)$") {
unset beresp.http.Set-cookies;
# --------------------------------------------
set resp.http.X-Cache = "HIT via " + server.ip;
set resp.http.X-Cache = "MISS from " + server.ip;