我是 Varnish 新手。在编辑后端选择器子例程时,我发现自己在 Varnish 配置文件中寻找早期返回模式。
sub select_backend {
if (req.http.host ~ "tracking\..*") {
set req.backend = tracking;
}
if (req.http.host ~ "myapp1.domain.com") {
if (req.url ~ "^/insecure/path") {
error 403 "Forbidden";
}
set req.backend = app1;
}
if (req.http.host ~ "myapp2.domain.com") {
set req.backend = app2;
}
}
sub vcl_recv {
// other stuffs
call select_backend;
}
如果没有正确的返回/退出语句,则存在更改后端两次的风险(随着文件变得越来越复杂)。
是否可以使用提前返回模式来避免这种情况?如果不是,如何避免使用 if
/elseif
模式而不浪费性能?
最佳答案
目前没有什么好的办法可以做到这一点,如Syntax part of VCL Basics解释:
The "return" statement of VCL returns control from the VCL state engine to Varnish. If you define your own function and call it from one of the default functions, typing "return(foo)" will not return execution from your custom function to the default function, but return execution from VCL to Varnish. That is why we say that VCL has terminating statements, not traditional return values.
Some other people有类似的需求,建议是:
if (req.http.host ~ "tracking\..*") {
set req.backend = tracking;
} elsif (req.http.host ~ "myapp1.domain.com") {
if (req.url ~ "^/insecure/path") {
error 403 "Forbidden";
}
set req.backend = app1;
} elsif (req.http.host ~ "myapp2.domain.com") {
set req.backend = app2;
}
如果您保留模式if .. elsif
,则不应有机会设置后备两次。如果您保留单独的 if { }
block ,则可能会发生这种情况。
关于optimization - Varnish,具有提前退出功能的自定义子例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29077530/