Nginx 中检测客户端不包含 Cookie:abc 即禁止访问怎么写?

2016-12-20 00:10:07 +08:00
 nikoo
即所有访问客户端必须包含一个 cookie 名为 abc ,如不包含该 cookie 即禁止访问

不在服务器端处理,仅在 nginx 中是否可以做到?谢谢!
4596 次点击
所在节点    NGINX
10 条回复
Phant0m
2016-12-20 00:25:26 +08:00
ngx lua 可以实现
lhbc
2016-12-20 00:54:49 +08:00
map $COOKIE_abc
shiniv
2016-12-20 01:29:48 +08:00
试试这样能能否符合你的需求

set $auth_cookie 0;
if ($http_cookie ~* "AUTH_COOKIE=([a-z0-9]+)(?:/|$)") {
set $auth_cookie 1;
}

if ($auth_cookie = 0) {
return 403;
}
jarlyyn
2016-12-20 01:39:47 +08:00
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

我线上在用的
nikoo
2016-12-20 03:13:11 +08:00
@jarlyyn 谢谢,很有帮助

如果仅判断 cookie 是否存在怎么处理?实际生产环境中 abc 的 cookie 值每个用户是不同的,没法这样写在配置里判断
jarlyyn
2016-12-20 03:37:22 +08:00
@nikoo

就是 if 那一句
nikoo
2016-12-20 09:20:30 +08:00
@jarlyyn

if ( $cookie_antiscanpassword != "password") {
这句是判断名为 antiscanpassword 的 cookie 值是否为 "password" 吧?而不是判断 antiscanpassword 是否存在
jarlyyn
2016-12-20 10:05:46 +08:00
@nikoo

应该是直接 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.
AlexaZhou
2016-12-20 11:20:10 +08:00
不想太麻烦的话,可以试试 VeryNginx
TaMud
2016-12-20 13:32:31 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/328758

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX