我正在尝试设置一个中间 Varnish 服务器,以允许 xyz.com 上的 Rails 应用程序在其他几个域名上工作。
Rails 应用程序不时会输出一些 301/302 重定向,显然 varnish 不会更改这些 header ,因此访问者会被重定向到原始站点(位于面向公众的 varnish 服务器后面),所以...错误。
有没有办法在 Varnish 方面配置这种重写?
在 vcl_fetch 下我尝试了以下操作:
if ( (beresp.status == 301) || (beresp.status == 302) ) {
set req.url = regsub(req.url,".*",regsuball(regsub(beresp.http.Location,"^http://[^/]+(.*)","\1"),"[+]","%2520"));
return(restart);
但也许我不明白这是如何工作的?任何帮助将不胜感激
最佳答案
在与您的正则表达式抗争之后思考用例...我认为您可能可以做一件更直接的事情,例如重写位置并缓存更正的对象(并将重定向留给客户端浏览器)。
在 vcl_fetch
上:
# ...
if ( beresp.status == 301
|| beresp.status == 302
) {
# Check if we're redirecting to a different site
if ( ! beresp.http.Location ~ req.http.host ) {
# Rewrite HTTP Location header to cache it and pass redirection to client
set beresp.http.Location = regsub(
beresp.http.Location,
"^http://[^/]+/",
"http://" + req.http.host + "/"
);
}
}
# ...
如果您仍然希望在 Varnish 中的不同 url 上重新启动请求,我会尝试(再次在 vcl_fetch
上):
# ...
if ( beresp.status == 301
|| beresp.status == 302
) {
# Add a header so you can debug cleanly on varnishlog
set req.http.X-Redirected-Orig = beresp.http.Location;
# Rewrite request host
set req.http.host = regsub(
regsub(
beresp.http.Location,
"^http://",
"",
),
"^([^/]+)/.*$",
"\1"
);
# Rewrite request url
set req.url = regsub(
beresp.http.Location,
"^http://[^/]+/(.*)$",
"/\1",
);
# Add a header so you can debug cleanly on varnishlog
set req.http.X-Redirected-To = "http://" + req.http.host + req.url;
return (restart);
}
# ...
PS:请原谅我的 regsub 缩进,但我认为它的可读性更高。
关于ruby-on-rails - Varnish 缓存 http 301 302 header 位置重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20707490/