通过VCL从varnish发回自定义响应

时间:2014-07-02 00:04:37

标签: varnish varnish-vcl

有没有办法从varnish本身发回自定义回复?

if (req.url ~ "^/hello") {
  return "hello world";
}

2 个答案:

答案 0 :(得分:9)

您可以使用synthetic响应执行此操作。例如:

sub vcl_recv {
  if (req.url ~ "^/hello") {
    error 700 "OK";
  }
}

sub vcl_error {
  if (obj.status == 700) {
    set obj.http.Content-Type = "text/html; charset=utf-8";
    set obj.status = 200;
    synthetic {"
     <html>
       <head>
          <title>Hello!</title>
       </head>
       <body>
          <h1>Hello world!</h1>
       </body>
     </html>
    "};
  }
}

答案 1 :(得分:3)

我认为通过vcl_synth子程序在Varnish 4中执行此操作的首选方法是:

sub vcl_recv {
    if (req.url ~ "^/hello") {
        # We set a status of 750 and use the synth subroutine
        return (synth(750));
    }
}

sub vcl_synth {
    if (resp.status == 750) {
        # Set a status the client will understand
        set resp.status = 200;
        # Create our synthetic response
        synthetic("hello world");
        return(deliver);
    }
}

有关内置子程序的更多信息:

http://book.varnish-software.com/4.0/chapters/VCL_Built_in_Subroutines.html#vcl-vcl-synth