Last active
February 10, 2017 20:34
-
-
Save rezan/c23b40311c3af0623e1eddfe63064aa6 to your computer and use it in GitHub Desktop.
Self routing Varnish Cache cluster example using 302 redirects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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