简体   繁体   中英

Unable to reference cookie value in htaccess with %1

I'm yet another person new to .htaccess files and having difficulty with it. I'm trying to have the file check for a cookie named 'path' and then see if the URI contains it. I am trying to use %1 in the correct manner to reference the cookie value later in the file and I cannot seem to make it work properly. Here is my .htaccess file:

RewriteEngine On
#checking the cookie matches successfully
RewriteCond %{HTTP_COOKIE} path=/testing/rockwell/
#checking if the URI contains %1 (the value of the cookie) fails
RewriteCond %{REQUEST_URI} %1
#a literal string match works though
###RewriteCond %{REQUEST_URI} /testing/rockwell/  
RewriteRule .* http://www.example.com

What am I doing wrong with %1? I understand that it is supposed to allow me to reference a previous match in RewriteCond. I included the commented-out RewriteCond to show what I am trying do. Any help with this would be much appreciated.

So I ended up figuring it out, here's all the important stuff:

First, I needed to be using parentheses to capture the value of the cookie in the first place. Second, you can only use % or $ on the left side of a condition or rule, not the right side (since it is for RegEx). Now, it is possible to still compare two left-side values against each other, with a very neat and ill-documented trick submitted by Jon Lin to this question %N backreference inside RewriteCond . I had to modify the line a bit to fit my own usage, so here it is (for reference):

RewriteCond %{HTTP_COOKIE} path=(.*)
RewriteCond %1::%{REQUEST_URI} ^(.*)::\1
RewriteRule .* - [L]

This code checks if the value of the cookie is found at the beginning of the URI of the request, and does nothing if so. Any rule written after this will be executed if a match is not made.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM