请教 nginx deny 优先级的问题。

19 天前
 ab

http{ deny 192.168.6.8; ... server { listen 443 ssl; http2 on; server_name example.com; ... if ($http_user_agent ~* "curl") { return 406; } } } 客户端 192.168.6.8 使用 curl -I example.com 时,返回 406 ,难道 if 比 http 段的 deny ip 的优先级还高吗?

1433 次点击
所在节点    NGINX
9 条回复
gesse
19 天前
```
http{
deny 192.168.6.8;
server {
listen 443 ssl;
http2 on;
server_name example.com;
if ($http_user_agent ~* "curl") {
return 406;
}
}
}
```
- deny 指令 会拒绝访问并返回 403 状态码,但它不会停止后续配置的解析。
- if 语句 仍然会被执行,并可能修改或覆盖之前的响应状态。
GeekGao
18 天前
当客户端( 192.168.6.8 )发起请求时,首先检查的是 http 块中的 deny 指令。
如果 IP 地址被允许访问,则继续处理请求。
请求进入 server 块,在这里执行 if ($http_user_agent ~* "curl") 条件。这个条件是在请求处理过程中动态评估的,而不是在初始连接阶段。
因为 $http_user_agent 变量是基于实际请求头生成的,所以它可以覆盖之前的 deny 指令。

如果想完全阻止特定 IP 地址的访问,无论其 UA 如何,你可以考虑在 server 块中使用 if ($remote_addr = 192.168.6.8) 条件。
GeekGao
18 天前
所以,盲猜应该是 if 指令优先级的问题
ab
18 天前
@GeekGao
@gesse

谢谢两位大佬,目前还是不能确定,文档翻了半天也没看到优先级的说明。chatgpt 和 gemini 则都是一口咬定 http 的 deny 优先,正常应该返回 403
ladypxy
18 天前
你这就最常见的配置错误啊,官方文档就专门有一段,搜索 nginx if is evil

https://github.com/nginxinc/nginx-wiki/blob/836ecd605a1b9861fb608e848336bca9b8640b54/source/start/topics/depth/ifisevil.rst
ab
18 天前
@ladypxy 原来如此,谢谢!
gesse
17 天前
@ladypxy
这个文章貌似是说 if 在 location 里的问题,OP 的设置并没有在 location 里。
ab
17 天前
@gesse 其实是一样的,一个 if 相当于一个 location
usernametoolong
17 天前
if 加一个 break ?

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

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

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

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

© 2021 V2EX