Apache Redirect:基于Cookie值的RewriteRule

时间:2015-12-22 08:49:16

标签: regex apache redirect cookies url-rewriting

我正在使用Apache 2.2并且想要在请求URI中添加字符串(如果它还不是URI的一部分)。该字符串是动态的,存储在名为“mycookie”的cookie中。如果cookie值为“root”,则不应执行重写。

案例1:重写所需
的myCookie = FOO
uri = / bar - > uri = / foo / bar(/ foo已添加)

案例2:不需要重写
的myCookie = FOO
uri = / foo / bar - >没有重写(URI已经以/ foo开头)

案例3:不重写,忽略cookie值
的myCookie =根
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]

问题是请求在循环中重写。 - > /富/富/富/../富/酒吧

解决方案反向引用(%1)只能在RewriteCond的左侧使用

1 个答案:

答案 0 :(得分:1)

反向引用(%1)只能在RewriteCond的左侧使用

更改了RewriteCond%{REQUEST_URI} ^。 /%1 /. $ [NC]

RewriteCond%1 ::%{REQUEST_URI} ^(。*?):: / \ 1 /?