# This is an example VCL file for Varnish.
#
# It does not do anything by default, delegating control to the
# builtin VCL. The builtin VCL is called when there is no explicit
# return statement.
#
# See the VCL chapters in the Users Guide at https://www.varnish-cache.org/docs/
# and for more examples.
# Marker to tell the VCL compiler that this VCL has been adapted to the
# new 4.0 format.
vcl 4.0;
import directors;
probe check {
.url = "/";
.window = 5;
.threshold = 4;
.interval = 2s;
.timeout = 1s;
}
backend websrv1 {
.host = "10.1.10.66";
.port = "80";
.probe = check;
}
backend websrv2 {
.host = "10.1.10.67";
.port = "80";
.probe = check;
}
sub vcl_init {
new websrv = directors.round_robin();
websrv.add_backend(websrv1);
websrv.add_backend(websrv2);
}
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$") { #将.php结尾的文件发往websrv1
set req.backend_hint = websrv1;
} else {
set req.backend_hint = websrv2; #将其他结尾的文件发往websrv1
}
if (req.url ~"(?i)^/login") {
return(pass);
}
if ( req.method == "PURGE") {
return(purge);
}
}
sub vcl_purge {
return(synth(200,"Pugred."));
}
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.
if (beresp.http.cache.control !~ "s-maxage") {
if (bereq.url ~ "(?i)\.jpg$") {
set beresp.ttl = 3600s; #设置.jpg结尾的图片TTL时长,加长其缓存时长
unset beresp.http.Set-Cookie; #取消追踪图片的cookie信息
}
}
if (beresp.http.cache.control !~ "s-maxage") {
if (bereq.url ~ "(?i)\.css$") {
set beresp.ttl = 3600s;
unset beresp.http.Set-Cookie;
}
}
}
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;
}
}
实验图:
将动态页面发往websrv1,实现动静分离效果。
将动态静态页面发往websrv2,实现动静分离效果。