6

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]

marked as duplicate by Jenny D, Rex, Tim Brigham, Dave M, mdpc Mar 14 '14 at 1:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 4
    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 4:31
7

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 ......
4

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.

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]

  • 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 3:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.