【发布时间】:2015-12-28 22:56:21
【问题描述】:
我正在使用 Apache 2.2,如果它还不是 URI 的一部分,我想将一个字符串添加到请求 URI。该字符串是动态的并存储在名为“mycookie”的 cookie 中。如果 cookie 值为“root”,则不应执行重写。
案例 1:需要重写
我的cookie=foo
uri=/bar -> uri=/foo/bar(添加了/foo)
案例 2:无需重写
我的cookie=foo
uri=/foo/bar -> 不重写(URI 已经以 /foo 开头)
案例 3:不重写,cookie 值被忽略
我的cookie=root
uri=/bar -> 不重写(忽略值“root”)
#no redirect for cookie value „root“
RewriteCond %{HTTP_COOKIE} ^.*mycookie=([a-zA-Z0-9-\.]+).* [NC]
RewriteCond %1 =root
RewriteRule ^(.*)$ - [L,NC]
#no rewrite required if cookie value is already part of the request uri
RewriteCond %{HTTP_COOKIE} ^.* mycookie=([a-zA-Z0-9-\.]+).* [NC]
# Wrong syntax
# RewriteCond %{REQUEST_URI} ^.*/%1/.*$ [NC]
# Correct syntax
RewriteCond %1::%{REQUEST_URI} ^(.*?)::/\1/?
RewriteRule ^(.*)$ - [L,NC]
#add cookie value to path: eg. /bar -> /cookieval/bar
RewriteCond %{HTTP_COOKIE} ^.* mycookie =([a-zA-Z0-9-\.]+).* [NC]
RewriteRule ^(.*)$ https://sub.domain.com/%1$1 [R,L]
问题是请求在循环中被重写。 -> /foo/foo/foo/../foo/bar
解决方案 反向引用 (%1) 只能用于 RewriteCond 的左侧
【问题讨论】:
-
我发现了问题所在。您只能在左侧的 RewriteCond 中使用反向引用 (%1)。我不得不将 RewriteCond %{REQUEST_URI} ^.*/%1/.*$ [NC] 更改为 RewriteCond %1::%{REQUEST_URI} ^(.*?)::/\1/?
标签: regex apache redirect cookies url-rewriting