Adding a Trailing Slash to Directories Using Varnish

July 7, 2011
wyvern-programming-languages-in-one

My web configuration makes use of Varnish as a front-end, and I noticed a bug recently where asking for "/study" was failing, while asking for "/study/" would succeed.

But when I moved Varnish out of the way, Nginx handled this without issue.

So I set out to figure out a recipe for adding the trailing slash within Varnish. The following solution works for me, but if you know a better way do let me know.

# If the requested URL contains $directory and doesn’t contain index.php, add a trailing slash to the end.

sub vcl_recv {
if ((req.url ~ "/directory" ) && (! (req.url ~ "index.php"))){
   set req.url = req.url "/";
}
}

::

supporting = loving

Since 1999 I've been creating ad-free technical tutorials and essays here. It's a one-person effort that's also my life and livelihood. If it makes your day more livable in any way, please consider supporting the work with a monthly or one-time donation. Your support means a lot to me, and makes all the difference. 🫶🏼