I have a cookie for language. I want to check if this cookie is set and to check its value to redirect the user to specific page.
the cookie name is Lang and its value might be En,Fr,or Ar
if (req.http.Cookie ~ "Lang"){ //now i want to check for the cookie value //if LANG=="Ar" // set req.url = req.url "CookieValue" }
anybody know how to check for cookie value in varnish??
Thanks
Best Answer
Since all the cookies - both name and value - are in the
req.http.Cookie
string, you should be able to check for both name and value at the same time. Unfortunately, Varnish does not have any specialized methods for dealing with cookies - you must use regular expressions.It is important to note that cookies are delimited by a semicolon and white space, for example:
We know, therefore that our cookie is either at the start of req.http.Cookie, or is preceded by a semicolon and white space, and either ends with a semicolon, or is at the end of req.http.Cookie. Given this, we can construct a regex that will match our cookie and the semicolon, if any. Something like:
Briefly, going through the above we have:
^
means start of string|
means OR;
is taken literally (i.e. semicolon)\s
means white space*
means one or more repetitions of the preceding characterLang
is the name of the cookieEn
is the value of the cookie;
is taken literally (i.e. semicolon)|
means OR$
means end of stringUsing the above, we can check for the cookies and perform some action on them:
There may be better ways, or more efficient regexes (unfortunately, varnish doesn't have user defined variables - which means you can't use regex capture groups) - but hopefully this will do the job.
Arguably, you could construct a regex with a capture group using regsub, and set that as a subdomain, perhaps something like:
In the case of 'Lang=en', you would capture the 'en' add a period (.) and prepend to 'example.com' giving you en.example.com. I'd suggest though directly using a cookie to set the URL - without a lot of error checking - would be a very bad solution. If you just have 3 languages, a couple of if statements and a default would be much safer.
Note: the above is untested, and regexes aren't my forte - expect a few mistakes - but hopefully the premise works.