9

How do I make my rule match an exact value of a cookie? I've tried:

RewriteCond %{HTTP_COOKIE} ^its=me$ [NC]

RewriteCond %{HTTP_COOKIE} its=^me$ [NC]

RewriteCond %{HTTP_COOKIE} its="me" [NC]

RewriteCond %{HTTP_COOKIE} its=me [NC] 

The last almost works, but matches when extra text is at the end of the value, like "me2". The condition should be true only if the its cookie has an exact value of me, with nothing more before or after.

These values should not match:

  • you
  • me2
  • [empty string]
  • [cookie is not set at all]
Nick
  • 4,433
  • 29
  • 67
  • 95
  • 6
    The page at the "already has an answer" link doesn't even contain the word "cookie". This is a useful question as is. – Stan James Aug 13 '15 at 04:31

3 Answers3

8

There could be of course several cookies, and they can be URL escaped, making comparisons tricky.

Something like this ought to work in most cases:

RewriteCond %{HTTP_COOKIE}     its=([^;]+) 
RewriteCond %1                 ^me$
RewriteRule ......

If you need to unescape the cookie you can add a rewritemap for that:

RewriteMap unescape int:unescape

RewriteCond %{HTTP_COOKIE}     its=([^;]+) 
RewriteCond %{unescape:%1}     ^me$
RewriteRule ......
Krist van Besien
  • 1,832
  • 13
  • 16
3

It doesn't need to be more complicated than

RewriteCond %{HTTP_COOKIE}     /^(.*;)?its=me(;.*)?$/

Note that if the cookie value contains special (not URL-safe) characters, Krist van Besien's solution probably works best.

Erwin Wessels
  • 161
  • 1
  • 6
  • 1
    Regex in the _CondPattern_ (`RewriteCond` directive) are not delimited with slashes (they are delimited with _spaces_ - standard argument delimiters in Apache config files). In the above example, the slashes at the start and end of the regex are matched literally. However, cookie name=value pairs in the `Cookie` header are often delimited by `;`, so even without the slash "delimiters", this will only match if `its=me` happens to occur at the very start of the `Cookie` header. The regex should be something like this instead: `^(.*;\s?)?its=me(;.*)?$` – MrWhite Dec 02 '21 at 23:34
1

From the online docs:

'=CondPattern' (lexicographically equal)
Treats the CondPattern as a plain string and compares it lexicographically to TestString.True if TestString is lexicographically equal to CondPattern (the two strings are exactly equal, character for character). If CondPattern is "" (two quotation marks) this compares TestString to the empty string.

Does this work?

RewriteCond %{HTTP_COOKIE} =its=me [NC]

dawud
  • 14,918
  • 3
  • 41
  • 61
  • 1
    Unfortunately it won't match if the `Cookie` header contains multiple cookies, since they're all combined into the one string. – Simon East Jul 27 '15 at 03:48