ruby-on-rails - Varnish 缓存 http 301 302 header 位置重定向

标签 ruby-on-rails linux centos varnish varnish-vcl

我正在尝试设置一个中间 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/

相关文章:

linux - Varnish 错误 : vcl. 加载/etc/varnish/default.vcl 失败

c - 在 C 中与程序同时运行线程

php - 如何在 Centos 中安装 PHP 5.3 - mhash?

MySQL ERROR 2026 - SSL 连接错误 - Ubuntu 20.04

node.js - 在 Centos 6.8 上安装 Node

ruby-on-rails - 如何在rails中更新推特

ruby-on-rails - 更改 Knock gem 生成的 JWT 身份验证 token 的有效期

php - 使用 nginx 和 fastcgi 捕获 PHP 404 错误

ruby-on-rails - 模拟 rspec 中的错误/异常(不仅仅是它的类型)

jquery - Rails jquery 日期选择器时区