Skip to content

Instantly share code, notes, and snippets.

@rezan rezan/self_route_302.vcl
Last active Feb 10, 2017

Embed
What would you like to do?
Self routing Varnish Cache cluster example using 302 redirects
# Self routing cluster example using 302 redirects
vcl 4.0;
import directors;
backend node1 {
.host = "node1.example.com";
.port = "80";
}
backend node2 {
.host = "node2.example.com";
.port = "80";
}
backend node3 {
.host = "node3.example.com";
.port = "80";
}
backend content {
.host = "content-origin.example.com";
.port = "80";
}
sub vcl_init
{
# We use a simple hash director to shard our content
new cluster = directors.hash();
cluster.add_backend(node1, 1);
cluster.add_backend(node2, 1);
cluster.add_backend(node3, 1);
}
sub vcl_recv
{
# Figure out where the content is
set req.backend_hint = cluster.backend(req.url);
set req.http.X-shard = req.backend_hint;
# Do we have the content? Did they come in with the right Host?
# If yes, reroute to the backend
# If not, redirect the request to the appropriate node
if (req.http.X-shard == server.identity &&
req.http.X-shard + ".example.com" == req.http.Host) {
set req.backend_hint = content;
} else {
set req.http.X-redir = "https://" + req.http.X-shard +
".example.com" + req.url;
return(synth(302, "Found"));
}
# Your VCL logic starts here
}
sub vcl_synth
{
if (resp.status == 302) {
set resp.http.Location = req.http.X-redir;
return (deliver);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.