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
andcookie2=2
exist.
Instead, all I ever get is cookie1
:
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?
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 theHTTP_COOKIE
variable, i.e.I don't know if this will solve your problem, but I can offer 2 things:
a hunch that even though you've ordered the directives properly [Header... SetEnvIf... Header...], the order of processing of the relevant modules providing those directives might make their interplay an issue. Which suggests an alternate angle of attack might be worth trying.
a different mechanism for the cookie-setting might help: try using a mod_rewrite RewriteRule that does not actually route the request (note the "-" target), but merely sets a cookie:
RewriteRule ^/index.html - [CO=cookiename:cookieval:.example.com:1440:/]
You can add a RewriteCond to check for the env var and thus conditionally set the cookie like this:
It might even meet your requirements to skip setting env vars altogether and just set the 2nd cookie based on the presence of the 1st, keeping all the logic within mod_rewrite:
HTH! :) Chris