How to use Apache SetEnvIf with cookie values

apache-2.2

I'm trying to control apache based on cookie values, but I can't seem to get SetEnvIf to work with HTTP_COOKIE. I've boiled this down to some simple logic to isolate the issue and be easy to test.

Apache 2.2.22 on Ubuntu 12.04.1 LTS.


What I'm using is:

     Header set Set-Cookie "cookie1=1"
     SetEnvIf HTTP_COOKIE "cookie1=1" is_cookie1
     Header set Set-Cookie "cookie2=2" env=is_cookie1

Using Chrome's resources tab, I am inspecting the cookies for the page. What I expect to see is:

  • First page load, cookie1=1 exists
  • Second (and subsequent) page loads, cookie1=1 and cookie2=2 exist.

Instead, all I ever get is cookie1:

Chrome cookie inspector


If I add the line:

     SetEnvIf Remote_Addr ^192\.168\. is_cookie1

Then cookie2 is set immediately, as I'd expect, so the last Header ... env=is_cookie1 line appears to be fine.


I also tried to verify that HTTP_COOKIE was being set correctly:

     RewriteRule ^/test/$ /test/%{HTTP_COOKIE} [R=302,L]

Now going to /test/ immediately redirects to /test/cookie1=1%3b%20cookie2=2 as I was expecting, and so HTTP_COOKIE seems to be set properly.


I've also tried a bunch of variations of SetEnvIf and nothing seems to work:

     SetEnvIf HTTP_COOKIE "^cookie1=1$" is_cookie1
     SetEnvIf HTTP_COOKIE ^cookie1=1$ is_cookie1
     SetEnvIf HTTP_COOKIE "^.+$" is_cookie1
     SetEnvIf HTTP_COOKIE ^.+$ is_cookie1

..although

     SetEnvIf HTTP_COOKIE ^.*$ is_cookie1

sets cookie2 immediately (on first load) in any situation (which… is not useful at all. but at least it tells me this line does something).


What am I doing wrong?

Best Answer

I was facing the same issue and this page comes at the top of Google for apache setenvif cookie so I thought I would share how I fixed this.

I was able to match against the cookies by using the Cookie variable rather than the HTTP_COOKIE variable, i.e.

SetEnvIf Cookie "cookie1=1" is_cookie1