Caching requests by HTTP status code

Sometimes you may want to cache request based on the status code with a different TTL.

Adding the following in the vcl_backend_response will help you in achieving the result:


if (beresp.status == 403 || beresp.status == 404 || beresp.status >= 500)
{
   set beresp.ttl = 60s;
}

Customizing 404 error page

In Varnish 3, in order to customize the error page you should customize the subroutine VCL_ERROR:

Things changes in Varnish 4, errors that occur in the backend server subroutine VCL_BACKEND_ERROR are processed used the SYNTH command in the VCL and defined by creating a specific synthetic object in the subroutine VCL_SYNTH.

Following a VCL example that generate a 404 managed by a synthetic object by invoking the following URL http://www.myservname.com:port/404 When you access to the URL, Synth (status_code, reason).


vcl 4.0;
import std;

sub vcl_recv {
    if (req.url ~ "^/404") {
        return (synth(999, "Generate a 404 error explicitly"));
    }
}
 
sub vcl_backend_response {
}
 
sub vcl_deliver {
}
 
sub vcl_backend_error {
    set beresp.http.Content-Type = "text/html; charset=utf-8";
    synthetic( {"errors due to backend fetch"} );
    return (deliver);
}
 
sub vcl_synth {
    if (resp.status == 999) {
        set resp.status = 404;
        set resp.http.Content-Type = "text/plain; charset=utf-8";
        synthetic(std.fileread("/tmp/vcl_404_error.html"));
        return (deliver);
    }
    return (deliver);
}

Remember to create the error page in the correct path:


$ cat /tmp//tmp/vcl_404_error.html
errors due to vcl

To test the response do the following:


$ curl -D - http://www.varnishservername.com:port/
HTTP/1.1 503 Backend fetch failed
Date: Sun, 08 Feb 2015 09:26:35 GMT
Server: Varnish
Content-Type: text/html; charset=utf-8
X-Varnish: 2
Age: 0
Via: 1.1 varnish-v4
Content-Length: 27
Connection: keep-alive
 
errors due to backend fetch

$ curl -D - http://www.varnishservername.com:port//404/foo
HTTP/1.1 404 Not Found
Date: Sun, 08 Feb 2015 09:26:39 GMT
Server: Varnish
X-Varnish: 5
Content-Type: text/plain; charset=utf-8
Content-Length: 18
Connection: keep-alive
 
errors due to vcl