【问题标题】:varnish cache http 301 302 header location redirects清漆缓存 http 301 302 标头位置重定向
【发布时间】:2014-01-09 13:03:27
【问题描述】:

我正在尝试设置一个中间清漆服务器,以允许 xyz.com 上的 Rails 应用程序在其他几个域名上工作。

发生的情况是,Rails 应用程序有时会输出一些 301/302 重定向,而 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);

但也许我不明白这是如何工作的?任何帮助将不胜感激

【问题讨论】:

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


    【解决方案1】:

    在与您的正则表达式进行斗争之后,考虑用例......我认为您可能会做一件非常简单的事情,例如重写位置并缓存更正的对象(并将重定向留给客户端浏览器)。

    开启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 缩进,但我认为它更具可读性。

    【讨论】:

      猜你喜欢
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 2011-05-16
      • 2018-04-09
      • 2019-01-14
      相关资源
      最近更新 更多