Reverse-Proxy

Varnish:根據 URL 使用多個後端

  • February 18, 2020

我有幾個內部站點,我想通過插入帶有清漆的 url 來訪問它們。例如,如果鍵入

   http://www.example.com/serv1/--->http://192.168.0.1/application1
   http://www.example.com/serv2/--->http://192.168.0.1/application2

但是,目前我不明白如何配置清漆。我目前的配置如下:default.vlc

   vcl 4.0;

   backend vm1 {
       .host = "www.example.com";
       .port = "81";
       .connect_timeout = 6000s;
       .first_byte_timeout = 6000s;
       .between_bytes_timeout = 6000s;
   }

   backend serv1 {
       .host = "192.168.0.1";
       .port = "80";
       .connect_timeout = 6000s;
       .first_byte_timeout = 6000s;
       .between_bytes_timeout = 6000s;
   }

   backend serv2 {
       .host = "192.168.0.3";
       .port = "80";
       .connect_timeout = 6000s;
       .first_byte_timeout = 6000s;
       .between_bytes_timeout = 6000s;
   }

   sub vcl_recv {
          if (req.url == "^/serv1/*$") {
              set req.url = regsub(req.url, "^/serv1/*$","/application1");
              set req.backend_hint = serv1;
          } else {
       set req.backend_hint = vm1;
       }

          if (req.url == "^/serv2/*$") {
              set req.url = regsub(req.url, "^/serv1/*$","/application2");
              set req.backend_hint = serv2;
          } else {
       set req.backend_hint = vm1;
       }          
}

你的意思可能是:

http://www.example.com/serv1/--->http://192.168.0.1/application1
http://www.example.com/serv2/--->http://192.168.0.3/application2

無論哪種方式,您都必須重寫Host標題。並使用適當的正則表達式:

vcl 4.0;

backend vm1 {
   .host = "www.example.com";
   .port = "81";
   .connect_timeout = 6000s;
   .first_byte_timeout = 6000s;
   .between_bytes_timeout = 6000s;
}

backend serv1 {
   .host = "192.168.0.1";
   .port = "80";
   .connect_timeout = 6000s;
   .first_byte_timeout = 6000s;
   .between_bytes_timeout = 6000s;
}

backend serv2 {
   .host = "192.168.0.3";
   .port = "80";
   .connect_timeout = 6000s;
   .first_byte_timeout = 6000s;
   .between_bytes_timeout = 6000s;
}

sub vcl_recv {
      if (req.url == "^/serv1($|/)") {
          set req.url = regsub(req.url, "^/serv1","/application1");
          set req.http.host = "192.168.0.1";
          set req.backend_hint = serv1;
      } else {
          set req.backend_hint = vm1;
      }

      if (req.url == "^/serv2($|/)") {
          set req.url = regsub(req.url, "^/serv2","/application2");
          set req.http.host = "192.168.0.3";
          set req.backend_hint = serv2;
      } else {
         set req.backend_hint = vm1;
      }          
}

引用自:https://serverfault.com/questions/875313