Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending custom response back from varnish through VCL

Is there any way to send back custom responses from varnish itself?

if (req.url ~ "^/hello") {
  return "hello world";
}
like image 896
Vlad the Impala Avatar asked Dec 02 '22 19:12

Vlad the Impala


2 Answers

You would do this with a synthetic response. For example:

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>
    "};
  }
}
like image 149
Ketola Avatar answered Dec 28 '22 10:12

Ketola


I think the preferred way to do this in Varnish 4 via the vcl_synth subroutine:

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);
    }
}

There's some more info about the built-in subroutines at:

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

like image 37
Ross Motley Avatar answered Dec 28 '22 09:12

Ross Motley