简体   繁体   English

无法使用 %1 引用 htaccess 中的 cookie 值

[英]Unable to reference cookie value in htaccess with %1

I'm yet another person new to .htaccess files and having difficulty with it.我是 .htaccess 文件的另一个新手,并且遇到了困难。 I'm trying to have the file check for a cookie named 'path' and then see if the URI contains it.我正在尝试让文件检查名为“path”的 cookie,然后查看 URI 是否包含它。 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.我正在尝试以正确的方式使用 %1 以在文件中稍后引用 cookie 值,但我似乎无法使其正常工作。 Here is my .htaccess file:这是我的 .htaccess 文件:

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?我对 %1 做错了什么? I understand that it is supposed to allow me to reference a previous match in RewriteCond.我知道它应该允许我在 RewriteCond 中引用之前的匹配项。 I included the commented-out RewriteCond to show what I am trying do.我包含了注释掉的 RewriteCond 以显示我正在尝试做什么。 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.首先,我首先需要使用括号来捕获 cookie 的值。 Second, you can only use % or $ on the left side of a condition or rule, not the right side (since it is for RegEx).其次,您只能在条件或规则的左侧使用 % 或 $,而不能在右侧使用(因为它用于 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 .现在,仍然可以将两个左侧的值相互比较,使用 Jon Lin 提交的一个非常简洁且记录不全的技巧,用于RewriteCond 内的这个问题%N 反向引用 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.此代码检查是否在请求的 URI 的开头找到了 cookie 的值,如果是,则不执行任何操作。 Any rule written after this will be executed if a match is not made.如果不匹配,则在此之后编写的任何规则都将被执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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