Search code examples
regexvarnishvarnish-vcl

Varnish cache subdirectories using regex


Using Varnish 4 I'm trying to cache a specific style of url: one with a certain number of directories:

if (req.url ~ "(?Ui)^/cars/.+/.+/.+/$") {
  return(hash);
}

This should MATCH the following:

/cars/only/four/subdirectories/
/cars/a/b/c/

However, it should not match these:

/cars/not/five/sub/directories/
/cars/not/four/and/some.html
/cars/not/three/
/cars/not_two/

However, the code I have seems to match anything with a trailing / (effectively ^/cars/.*/$). Where am I going wrong?

EDIT: a bit of further testing and I was wrong about the 'effectively' part. It seems to match four or more directories - only those that end in a trailing /


Solution

  • You seem to be trying to make . match anything other than /, so it would make sense to define it that way:

    "(?Ui)^/cars/[^/]+/[^/]+/[^/]+/$"
    

    Otherwise, it matches anything (including /).