11

我希望有人帮助我在 htaccess 中使用 if-else 语句。我想要的是 htaccess 读取 cookie 并检查它的值是否等于定义的值。如果它评估为假,它应该执行重定向并阻止访问请求的文件夹。如果评估返回 false,也许所有人都拒绝会更好。

我知道以下代码检查是否设置了命名 cookie 值。如果没有设置,它将执行它下面的重写规则。但是我怎样才能调整这条线,以便它检查它是否等于某个值?

RewriteEngine On
RewriteCond %{HTTP_COOKIE} !^.*cookie_name.*$ [NC]
RewriteRule .* http://www.google.com [NC,L]

我想要什么,但采用 .htaccess 风格:

if ($_COOKIE['cookie_name'] != 'specific_value'){
//rewrite_rule or deny from all.
}
4

4 回答 4

18

你很近。cookie 字符串需要一个=

RewriteEngine On
RewriteCond %{HTTP_COOKIE} !cookie_name=specific_value; [NC]
RewriteRule ^ http://www.google.com [NC,L]
于 2013-10-15T13:19:19.010 回答
8

替换required_value为需要匹配的值。

RewriteEngine On
RewriteCond %{HTTP_COOKIE} !cookie_name=required_value;? [NC]
RewriteRule ^ http://www.google.com [R=301,L]

;?确保匹配发生在有多个 cookie 值对或cookie_name唯一 cookie 集时。这也可以防止匹配 cookie 值,例如off仅需要匹配of(子字符串)时。

于 2013-10-15T13:20:01.873 回答
1

您可以使用以下代码检查 cookie 中的特定值:

RewriteEngine On

RewriteCond %{HTTP_COOKIE} !cookie_name=specific_value [NC]
RewriteRule ^ http://www.google.com [NC,L,R=302]
于 2013-10-15T13:18:48.833 回答
0

The %{HTTP_COOKIE} string looks like a series of escaped name-value pairs separated by semicolons, and each semicolon is followed by a space. From MDN:

Syntax

Cookie: <cookie-list>
Cookie: name=value
Cookie: name=value; name2=value2; name3=value3

<cookie-list>

  • A list of name-value pairs in the form of =. Pairs in the list are separated by a semicolon and a space ('; ').

Examples

Cookie: PHPSESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1

So in your regular expression, you need to optionally match the semicolon followed by a space at the beginning and the semicolon at the end like so:

RewriteCond %{HTTP_COOKIE} "!(?:^|; )cookie_name=specific_value(?:;|$)"

Note: Different set-cookie functions escape different characters. So while one function might escape the @ symbol, another one might not causing inconsistencies in how your cookie string looks. For example a search for useremail@gmail.com might fail if it is stored as useremail%40gmail.com. They are both valid.

于 2020-10-24T14:54:15.837 回答