Note
Fastly is based on Varnish and offers a lot of easy-to-use UI on top of hosting. All the VCL here should be compatible with Varnish 2 excluding custom extensions.
Fastly offers the ability to create “synthetic” responses inside the engine itself. This means zero backend involvement in generating that response. Often times this is used in combination with an ESI or similar to speed up the response cycle but another benefit is the ability to include variables in the response itself. By doing the response creation inside the cache the backend isn’t bothered and everything runs much quicker.
My use case was simple, I wanted to include the requested URL in the 404 error page, but I didn’t want the URL added via JavaScript or similar. Here’s a quick example that returns a basic synthetic response including the requested URL:
# In vcl_fetch
if (beresp.status == 404) {
error 900;
}
# In vcl_error
if (obj.status == 900) {
set obj.http.Content-Type = "text/html";
synthetic {"<!DOCTYPE html><html><body>
The URL <code>"} req.url {"</code> was not found on this server.
"};
return(deliver);
}
I’m working with a much more complicated chunk of HTML which includes client-side JavaScript to offer suggestions based on the 404 response. For example, /sort.html suggests visiting the Sorting Algorithms post or Visual Sort demo page.
The best guide for learning which variables are available where is the VCL functions section of the Varnish Book. It follows normal logic (e.g. resp
isn’t available in vcl_fetch
because the response hasn’t been formed) however you can hit rides on other variables (typically by setting custom headers on req.http
) if you find the need to have something like obj.ttl
available in vcl_deliver
.
Custom response with Fastly
Here’s a step-by-step walk through for implementing the above. A key point is that it does not require custom VCL uploads to be enabled. Enabling custom VCL is trivial with a quick support ticket but it does open up some risk. Not sure you need it? Don’t enable it.
First, you’re going to open up the configuration.
And add a new response.
The name isn’t that important. The HTTP status code should be 404. The MIME type should be text/html
unless you’re serving a JSON or XML response.
Next add a condition to this response.
This response should be applied when the beresp
(backend response) returns with a 404 status code.
That’s it. Activate your new configuration and test it out.