Search code examples
cachingcookiesvarnishvarnish-vcl

How to check if value is number in Varnish?


Cookie String Example:

session=9urt2jipvkq77brfrf; MyId=124 ; PageId=134

I'm using Varnish version 4.1. In the following code, I extract the value of MyId (124) and PageId (134) from the cookie string and then check if the values are the same. If it is, return pass and don't serve cache content. The problem is that anonymous visitors will not have these two cookies in place unless they sign up, and it will accidentally pass the condition and not cache because both values will return the same value session=9urt2jipvkq77brfrf with the regsub function. I want to make sure that both values are entirely number. Is there any function handy for that?

Code:

if(req.http.Cookie){

   set req.http.MyId = regsub(req.http.Cookie,".*MyId=(\d+).*","\1");

   set req.http.PageId = regsub(req.http.Cookie,".*PageId=(\d+).*","\1");

   if(req.http.MyId == req.http.PageId){

       return (pass);
   }

}

Solution

  • There isn't a handy function like "is_integer" or similar. But you can check it with regular expressions.

    This will match any sequence of numbers:

    req.http.MyId ~ "[0-9]+"
    

    Or you can match only 3 numbers:

    req.http.MyId ~ "[0-9][0-9][0-9]"