Rendering arbitrary content with Varnish

Dave Clark
LoyaltyLion Engineering
1 min readMay 3, 2017

--

Example scenario: you use Varnish, and have some misbehaving third-party JS which is currently spamming your server with 404s for non-existent files like check.js. You want to return an empty 200 response from Varnish directly.

It’s pretty straightforward to do this in Varnish 4 (older versions will be slightly different) using the vcl_synth subroutine. First, add a rule in your vcl_recv like so:

if (req.url == "/check.js") {
return (synth(705, ""));
}

The synth tells Varnish you want to render a synthetic response, and passes control to vcl_synth, which you can define or add to as so:

sub vcl_synth {
if (resp.status == 705) {
set resp.status = 200;
set resp.http.Content-Type = "text/javascript";
synthetic(";");
return (deliver);
}
}

The Content-Type and content body (defined using the synthetic function) will depend on what you're sending back.

Note: if you’re using Varnish 5, you can now write directly to resp.body, instead of using the synthetic(...) function.

--

--