10

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]
1
  • 7
    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, 2015 at 4:31

3 Answers 3

9

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
  • 2
    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 ;<space>, 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 2, 2021 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]

1
  • 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, 2015 at 3:48

Not the answer you're looking for? Browse other questions tagged .