Last active
December 29, 2020 09:10
-
-
Save lavoiesl/6156632 to your computer and use it in GitHub Desktop.
Varnish ESI demo
http://blog.lavoie.sl/2013/08/varnish-esi-and-cookies.html
This file contains 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
<?php | |
header('Cache-Control: private'); | |
header('Pragma: no-cache'); | |
# Activate ESI processing | |
header('X-Esi: 1'); | |
?> | |
<!doctype html> | |
<html> | |
<head><title>Varnish test</title></head> | |
<body> | |
<p>This should NOT be cached:</p> | |
<pre> | |
Cookies: <?php print_r($_COOKIE); ?> | |
Timestamp: <?php echo microtime(true); ?> | |
</pre> | |
<hr> | |
<p>This should be cached:</p> | |
<esi:include src="partial.php" /> | |
<hr> | |
<p>This should be cached, but only if no Cookies are set:</p> | |
<esi:include src="partial.php?esi-cookies=1" /> | |
</body> | |
</html> |
This file contains 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
<?php | |
# This file is slow to generate and can be cached | |
# Shared cache only (Varnish) | |
header('Cache-Control: shared, smax-age=30'); | |
?> | |
<pre> | |
Cookies: <?php print_r($_COOKIE); ?> | |
Timestamp: <?php echo microtime(true); ?> | |
</pre> |
This file contains 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
sub vcl_recv { | |
if (req.esi_level > 0) { | |
# Backend may want to treat this request differently | |
set req.http.X-Esi-Level = req.esi_level; | |
if (req.url !~ "esi-cookies=1") { | |
unset req.http.cookie; | |
} | |
} else { | |
unset req.http.X-Esi-Level; # remove for security | |
} | |
} | |
sub vcl_fetch { | |
# Activate Edge Side Includes, but only if X-Esi header is present | |
if (beresp.http.X-Esi) { | |
set beresp.do_esi = true; | |
unset beresp.http.X-Esi; # remove header | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment