Apache rewrite rules: how to check hostname in cookies?

I set a cookie using rewrite rules and this works (simplified for brevity):

RewriteCond %{QUERY_STRING} set_cookie=1 [NC] RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI}?skip=1 [QSA,NE,NC,L,CO=test_%{HTTP_HOST}:tmp:%{HTTP_HOST}:5:/] 

This sets a cookie called test_ {host_name}. Now I want to read the cookie value of the next request. I tried this (and some options), but it does not work.

 RewriteCond %{QUERY_STRING} skip [NC] RewriteCond %{HTTP_COOKIE} ^.*test_%{HTTP_HOST}=tmp.*$ [NC] RewriteRule ^(.*)$ - [L] 

When I was googling, I found an article that stated the following:

If you are wondering: β€œWhy not use% {HTTP_HOST} instead of corz.org, create universal code?”, As far as I know, it is impossible to check one server variable against another using RewriteCond without using Atomic Back References and some serious POSIX 1003.2+ Jiggery -Pokery.

I assume that my problem, but I do not seem to understand how to solve it. Any help is appreciated.

Regards, Joost.

+6
source share
2 answers

I have found a solution. This part of my original question

 RewriteCond %{QUERY_STRING} skip [NC] RewriteCond %{HTTP_COOKIE} ^.*test_%{HTTP_HOST}=tmp.*$ [NC] RewriteRule ^(.*)$ - [L] 

should be replaced by the following

 RewriteCond %{QUERY_STRING} skip [NC] RewriteCond %{HTTP_HOST}@@%{HTTP_COOKIE} ^([^@]*)@@.*test_\1=tmp.* [NC] RewriteRule ^(.*)$ - [L] 

Only the second RewriteCond is changed. Its left side ( %{HTTP_HOST}@@%{HTTP_COOKIE} ) combines the http and cookie host values, using @@ as a glue (@@ doesn’t really mean something, it’s unlikely to be used on a regular host or file line cookie).

The right-hand side ( ^([^@]*)@@.*test_\1=tmp.* ) ^([^@]*)@@.*test_\1=tmp.* everything with the first "@", which is the host name, and then checks to see if it can be found somewhere in cookie values preceded by "test_" and then "= TMP".

+1
source

There is a useful trick in this area. This is a simple expression, but a unique mod_rewrite style.

Note. I'm not too careful about matching here, especially in the first condition - this is for illustration in the second condition:

 RewriteEngine ON RewriteCond %{HTTP_COOKIE} test_([^;]*)=tmp.*$ RewriteCond %1<>%{HTTP_HOST} ^(.+)<>\1 RewriteRule .* - [F] 

The new part (for mod_rewrite) is that you can only use / backrefs variables in the first argument, but you can use backrefs (for the current expression, not the previous one) in the second parameter.

A small <> is simply unlikely to appear as a delimiter.

+1
source

Source: https://habr.com/ru/post/975856/


All Articles