Nginx 中检测客户端不包含 Cookie:abc 即禁止访问怎么写?
- 0次
- 2021-05-20 20:35:05
- idczone
即所有访问客户端必须包含一个 cookie 名为 abc ,美国服务器如不包含该 cookie 即禁止访问
不在服务器端处理,仅在 nginx 中是否可以做到?谢谢!
ngx lua 可以实现
map $COOKIE_abc
试试这样能能否符合你的需求
set $auth_cookie 0;
if ($http_cookie ~* "AUTH_COOKIE=([a-z0-9]+)(?:/|$)") {
set $auth_cookie 1;
}
if ($auth_cookie = 0) {
return 403;
}
location / {
if ( $cookie_antiscanpassword != "password") {
return 403;
}
proxy_pass http://127.0.0.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
http://blog.jarlyyn.com/site/blogi/100-%E7%94%A8nginx%2Bcookie%E9%98%B2%E6%AD%A2%E7%AE%80%E5%8D%95%E7%9A%84%E6%8A%93%E5%8F%96%2F%E7%A0%B4%E8%A7%A3%E9%AA%9A%E6%89%B0
我线上在用的
谢谢,很有帮助
如果仅判断 cookie 是否存在怎么处理?实际生产环境中 abc 的 cookie 值每个用户是不同的,没法这样写在配置里判断
就是 if 那一句
if ( $cookie_antiscanpassword != "password") {
这句是判断名为 antiscanpassword 的 cookie 值是否为 "password" 吧?而不是判断 antiscanpassword 是否存在
应该是直接 if ( $cookie_antiscanpassword),不行的话正则处理 if ( $cookie_antiscanpassword~ .+)
参考 http://nginx.org/en/docs/http/ngx_http_rewrite_module.html
a variable name; false if the value of a variable is an empty string or “ 0 ”;
Before version 1.0.1, any string starting with “ 0 ” was considered a false value.
comparison of a variable with a string using the “=” and “!=” operators;
matching of a variable against a regular expression using the “~” (for case-sensitive matching) and “~*” (for case-insensitive matching) operators. Regular expressions can contain captures that are made available for later reuse in the $1..$9 variables. Negative operators “!~” and “!~*” are also available. If a regular expression includes the “}” or “;” characters, the whole expressions should be enclosed in single or double quotes.
checking of a file existence with the “-f ” and “!-f ” operators;
checking of a directory existence with the “-d ” and “!-d ” operators;
checking of a file, directory, or symbolic link existence with the “-e ” and “!-e ” operators;
checking for an executable file with the “-x ” and “!-x ” operators.
不想太麻烦的话,可以试试 VeryNginx
https://flfq.peuland.com/index.php/2014/09/03/%E5%A6%82%E4%BD%BF%E5%9C%A8nginx%E4%B8%8B%E9%98%B2%E7%9B%97%E9%93%BE%EF%BC%8C%E9%87%8D%E7%82%B9%E9%98%B2%E8%BF%85%E9%9B%B7/
有你要的答案