开发者

How to test many cookies in .htaccess with mod_rewrite?

I want to make an internal redirection based on the value of two cookies with use of htaccess/mod_rewrite. I don't know how to refer to both values of tested cookies with backreferences. Here is what I want to do:

foo = value_of_cookie_foo
bar = value_of_cookie_bar
if (foo AND bar) {
  RewriteRule ^(.*)$ mysite/fo开发者_JAVA技巧o/bar [R,L]
}

Sadly, the following code does not work. This is because (according to Apache documentation) backreferences apply only for the last RewriteCond. The first one is not taken into account.

 RewriteCond %{REQUEST_URI} ^/whatever$
 RewriteCond %{HTTP_COOKIE} cookie_foo=([^;]+) [NC]
 RewriteCond %{HTTP_COOKIE} cookie_bar=([^;]+) [NC]
 RewriteRule ^(.*)$ mysite/%1/%2 [R,L]

For cookie cookie_foo=foo; cookie_bar=bar; the above code redirects to http://mydomain.com/mysite/bar instead of http://mydomain.com/mysite/foo/bar.

Should I enclose testing of both cookies in one RewriteCond? How?


You should reorder the cookie values to get them both at once:

RewriteCond %{REQUEST_URI} ^/whatever$
RewriteCond %{HTTP_COOKIE} (^|;\s*)cookie_foo=([^;]+)
RewriteCond %2;%{HTTP_COOKIE} ^([^;]+)(;\s*|[^;])+cookie_bar=([^;]+) [NC]
RewriteRule ^(.*)$ mysite/%1/%3 [R,L]

This will put the cookie_foo value at the beginning to then get the cookie_bar value too.


Can you yry something like this for cookie check:

RewriteCond %{HTTP_COOKIE} cookie_foo=([^;]+);\scookie_bar=([^;]+);? [NC]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜