I would like somebody to help me with an if-else statement in htaccess. What I want is htaccess to read a cookie and check if its value equals a defined value. If it evaluat
The %{HTTP_COOKIE} string looks like a series of escaped name-value pairs separated by semicolons, and each semicolon is followed by a space. From MDN:
Syntax
Cookie: <cookie-list> Cookie: name=value Cookie: name=value; name2=value2; name3=value3
<cookie-list>
- A list of name-value pairs in the form of =. Pairs in the list are separated by a semicolon and a space ('; ').
Examples
Cookie: PHPSESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1
So in your regular expression, you need to optionally match the semicolon followed by a space at the beginning and the semicolon at the end like so:
RewriteCond %{HTTP_COOKIE} "!(?:^|; )cookie_name=specific_value(?:;|$)"
Note: Different set-cookie functions escape different characters. So while one function might escape the @ symbol, another one might not causing inconsistencies in how your cookie string looks. For example a search for useremail@gmail.com might fail if it is stored as useremail%40gmail.com. They are both valid.
You can use this code that checks for specific value in the cookie:
RewriteEngine On
RewriteCond %{HTTP_COOKIE} !cookie_name=specific_value [NC]
RewriteRule ^ http://www.google.com [NC,L,R=302]
Replace required_value
with the value that needs to be matched.
RewriteEngine On
RewriteCond %{HTTP_COOKIE} !cookie_name=required_value;? [NC]
RewriteRule ^ http://www.google.com [R=301,L]
;?
makes sure that the match happens both when there are multiple cookie value pairs or when cookie_name
is the only cookie set. This also prevents from matching on a cookie value like off
when a match on only of
(a substring) is required.
You're close. The cookie string needs a =
:
RewriteEngine On
RewriteCond %{HTTP_COOKIE} !cookie_name=specific_value; [NC]
RewriteRule ^ http://www.google.com [NC,L]