页面静态化
页面内容的拆分
- 静态内容
- 非状态相关的动态内容
- 状态相关的动态内容
HInclude CSI
用于pc或者h5页面
<hx:include src="/_fragment?path="></hx:include>
Varnish ESI
多用于app api的接口返回
vcl 4.0;
import directors;
backend server1 {
.host = "10.162.110.168";
.port = "80";
}
acl local {
"localhost";
}
sub vcl_init {
new director = directors.round_robin();
director.add_backend(server1);
}
sub vcl_recv {
set req.backend_hint = director.backend();
if (req.method == "PURGE") {
if (client.ip ~ local) {
return (purge);
} else {
return (synth(405));
}
}
if (req.http.Accept == "text/event-stream") {
return (pipe);
}
if (req.http.upgrade ~ "(?i)websocket") {
return (pipe);
}
if (req.method != "GET" && req.method != "HEAD") {
return (pass);
}
set req.http.Surrogate-Capability = "abc=ESI/1.0";
if (req.http.X-Forward-For) {
set req.http.X-Forward-For = req.http.X-Forward-For + "," + client.ip;
} else {
set req.http.X-Forward-For = client.ip;
}
return (hash);
}
sub vcl_backend_response {
if (beresp.http.Surrogate-Control ~ "ESI/1.0") {
unset beresp.http.Surrogate-Control;
set beresp.do_esi = true;
}
if (bereq.uncacheable) {
return (deliver);
}
set beresp.grace = 30s;
# 302 5xx no cache
if (beresp.status == 302 || beresp.status >= 500) {
set beresp.uncacheable = true;
set beresp.ttl = 120s;
return (deliver);
}
if (beresp.status == 301 || (beresp.status >= 400 && beresp.status < 500)) {
set beresp.ttl = 120s;
} else {
set beresp.ttl = 2400s;
}
unset beresp.http.Set-Cookie;
return (deliver);
}
sub vcl_pipe {
if (req.http.upgrade) {
set bereq.http.upgrade = req.http.upgrade;
}
return (pipe);
}
sub vcl_deliver {
set resp.http.X-Age = resp.http.Age;
unset resp.http.Age;
unset resp.http.Via;
unset resp.http.X-Powered-By;
unset resp.http.X-Varnish;
if (obj.hits > 0) {
set resp.http.X-Cache="HIT from " + server.hostname;
} else {
set resp.http.X-Cache="MISS";
}
return (deliver);
}
workflow
- varnish 接收到请求后,增加
Surrogate-Capability:abc=ESI/1.0
头,打到后端 - 后端判断
Surrogate-Capability
决定是否要使用esi标签来返回 (即判断这个请求是不是从varnish过来的) - 返回内容时判断是否含有
<esi:include
,增加Surrogate-Control:content="ESI/1.0"
头 - varnish 判断
Surrogate-Control
头,决定是否要启用 esi 替换
后端应用中的处理
生成路由url
/_fragment?path=
<hx:include src="/_fragment?path="></hx:include>
<esi:include src="/_fragment?path="></esi:include>
- 注册处理
/_fragment
路由