Performing HTTP redirections in Varnish
Varnish can perform HTTP redirections by returning a synthetic HTTP 301 response containing a Location header with the redirection endpoint.
Synthetic responses are triggered by a return (synth()) statement called from a client-side VCL subroutine. This also requires extending the vcl_synth logic and adding the necessary redirection logic.
HTTP to HTTPS redirections#
One of the most common types of HTTP redirection is HTTP to HTTPS.
Here’s an example where an HTTP request is redirected to its HTTPS equivalent:
vcl 4.1;
backend default {
.host = "127.0.0.1";
.port = 8080;
}
sub vcl_recv {
unset req.http.location;
if (std.port(server.ip) != 443) {
set req.http.location = "https://" + req.http.host + req.url;
return (synth (301));
}
}
sub vcl_synth {
if (resp.status == 301 ||
resp.status == 302 ||
resp.status == 303 ||
resp.status == 307) {
if (!req.http.location) {
std.log("location not specified");
set resp.status = 503;
return (deliver);
} else {
set resp.http.location = req.http.location;
return (deliver);
}
}
}
Redirecting internally#
Usually HTTP redirections are handled by rewrite rules on the origin webserver, but Varnish can perform these redirections as well.
Here’s a VCL example where we redirect requests for /some-page to /another-page:
vcl 4.1;
backend default {
.host = "127.0.0.1";
.port = 8080;
}
sub vcl_recv {
if (req.url == "/some-page") {
return (synth(301, "/another-page"));
}
}
sub vcl_synth {
if (resp.status == 301) {
set resp.http.location = resp.reason;
set resp.reason = "Moved";
return (deliver);
}
}
Redirecting to another site#
Not all redirections are internal. Sometimes it is necessary to redirect content to an external resource. This example redirects requests for /external to the https://external.example.com/ resource:
vcl 4.1;
backend default {
.host = "127.0.0.1";
.port = 8080;
}
sub vcl_recv {
if (req.url == "/external") {
return (synth(301,"https://external.example.com/"));
}
}
sub vcl_synth {
if (resp.status == 301) {
set resp.http.location = resp.reason;
set resp.reason = "Moved";
return (deliver);
}
}
