Home About News Products Blog

How can I deliver a custom response in Varnish Cache based on information received from an upstream service?


#1

How can I deliver a custom response based on information received from an upstream service?


#2

In Varnish you can utilize the vcl_synth method to create custom HTTP responses. Below is an example:

Say I receive a status code of 403 from an upstream service and want to deliver a custom HTML document to the client. First we’ll need to look for the status 403 in vcl_backend_response:

sub vcl_backend_response {
  if (beresp.status == 403) {
    return (synth(803, "Custom forbidden message"));
  }
}

This will intercept any request that has a status code of 403 and let you handle it with the vcl_synth block:

sub vcl_synth {
  if (resp.status == 803) {
    set resp.http.content-type = "text/html";
    set resp.status = 403;
    synthetic ({"
      <html>
      <body>
        <h1>
          You shall not pass - "} + resp.http.some-header + {"
        </h1>
      </body>
      </html>
    "});
    return (deliver);
  }
}