htaccess syntax - matching environment variables

#1
My site uses session cookies, which should be per session. So, I write the REMOTE_ADDR into the session cookie and want to check if it matches the current REMOTE_ADDR.

Apache config:
RewriteCond %{HTTP_COOKIE}      "bot=\d+"                       
RewriteCond %{HTTP_COOKIE}      !%{REMOTE_ADDR}                 
RewriteRule .*                  -                [E=referer:%{HTTP_COOKIE}]
That's (A) cookie exists and (B) does not match IP address, then (C) set a variable "referer" with the cookie. I then put the variable into the log, crammed into referer:

Code:
66.249.70.67 - - [15/Nov/2025:21:04:08 +0000] "GET /css.php?n=default&t=default HTTP/1.1" 200 5293 "bot=1_20251115130402_66.249.70.67" "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.122 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
So, the IP addresses match, but the second RewriteCond has a "!", so it should not have executed the RewriteRule. Why doesn't this work?
 
#2
Server variables (%{REMOTE_ADDR}) cannot be used for "CondPattern" as Apache and LiteSpeed expect an expression for the CondPattern.

For example, this would work:
Code:
RewriteCond %{REMOTE_ADDR} !^127\.0\.0\.1$

If you really need to compare a cookie with the client’s IP, use the newer expression engine:
Code:
RewriteCond expr "req('Cookie') !~ remote_addr"

or this
Code:
RewriteCond %{HTTP_COOKIE} (^|;\s*)ip=([^;]+)
RewriteCond %2 !=%{REMOTE_ADDR}
RewriteRule ...
 
#3
Thank you! Your second code snippet refers to a newer expression engine. Do you have a reference link to documentation? (Edit: I see this in the Apache 2.4 documentation. I wasn't aware that it had been added to LiteSpeed. But I haven't found anything mentioning req() or 'remote_addr in lower case.)

Your third code snippet makes me think that all I need to do to fix my version is to change "!" to "!=". Is that part of the newer expression engine as well? (Edit: I see this there also. It is a "lexicographic" comparison. I'm going to try this version...)
 
Last edited:
Top