Varnish Cache:如果会话处于活动状态,则重写 ESI 包含 URL

Varnish Cache:如果会话处于活动状态,则重写 ESI 包含 URL

我正在寻找在 Varnish 中重写 ESI 包含 url 的方法。

在我的模板中,我有:

<esi:include src="/esi/user.html" />

其中仅包含静态内容,即“欢迎客人”。

如果他们登录,我会将会话添加到我的.vcl 中。

我想要做的是将包含内容重写为:

<esi:include src="/esi/user.active.html" /> 

我将在那里进行数据库查询。

目前,在我的子 vcl_recv 中我有:

if (req.http.Cookie ~ "SessionId") {
        if (req.url ~ "^/esi/(.*)\.html") { 
        set req.url = regsub("^/esi/(.*)\.html", "$0", ".active"); 
        }
}

这会导致前端出现 503 错误。我该如何更新它以重写 URL 并使其正常工作?

答案1

好的,它工作正常。如果有人感兴趣的话,这是我的 .VCL 文件

backend default {
.host = "127.0.0.1";
.port = "8080";
}

sub vcl_recv {

 if (req.request != "GET" &&
        req.request != "HEAD" &&
        req.request != "PUT" &&
        req.request != "POST" &&
        req.request != "TRACE" &&
        req.request != "OPTIONS" &&
        req.request != "DELETE") {
        /* Non-RFC2616 or CONNECT which is weird. */
        return (pipe);
    }

# Remove cookie for static files
if (req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|woff|ttf|eot|svg)(\?[a-zA-Z0-9\=\.\-]+)?$") {
    remove req.http.cookie;
}

# Quick hack for now to clear the cache on post
if (req.request == "POST") {
    ban("req.http.host == "+ req.http.Host);
    return(pass);
}

# If CraftSessionId isn't active, remove cookies altogether
if (req.http.Cookie) {
    set req.http.Cookie = ";" + req.http.Cookie;
    set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
    set req.http.Cookie = regsuball(req.http.Cookie, ";(CraftSessionId)=", "; \1=");
    set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");

    if (req.http.Cookie == "") {
        remove req.http.Cookie;
    }
}


# If user is logged in/has cookies enabled, rewrite esi files to include *.active.html
if (req.http.cookie ~ "CraftSessionId=") {
    if (req.url ~ "^/esi") {
        set req.url = regsub(req.url, "^/esi/(.*).html", "/esi/\1-active.html");
    }
}

# Grace period for falldown
set req.grace = 1h;
}

sub vcl_fetch {

set beresp.ttl = 24h; # Make cache last 24 hours

#  Allow cookies in admin and account areas
    if (req.url !~ "(admin/login|account/login|account/register)") {
        unset beresp.http.set-cookie;
    }

set beresp.do_gzip = true;
set beresp.do_esi = true; # Allow ESI

# Grace period for falldown
set beresp.grace = 1h;

}

相关内容