Nginx 有办法对特定 ua 的请求进行速度限制吗

99 天前
 wu67

RT. 在服务器上建了 webdav 服务, 然后本地用 infuse 播放视频.

但是这播放器的缓存策略好像有点问题, 会一直不停的全速缓存整个视频,

我知道可以limit_rate ***k对 location 限速, 但是这是所有请求都限速了(有时候会想直接把文件全速下载回本地保存)

就想问问有没有办法能针对特定 ua 进行 limit_rate ?

1974 次点击
所在节点    NGINX
14 条回复
nashaofu
99 天前
两个功能都有的吧,组合下就可以用,if $http_user_agent ~* "ua" {}
wu67
99 天前
@nashaofu 好像不行啊。按语法思路,声明语句不能放在条件语句 if 里面
jinzc
99 天前
换用 openresty , 编码识别 ua 后限制速率
dropdatabase
99 天前
```
location / {
access_by_lua_block {
local limit_dict = ngx.shared.my_limit_dict
local ua = ngx.var.http_user_agent
local limit_key = "ua:" .. ngx.md5(ua)
local limit_count = limit_dict:get(limit_key) or 0

-- 设置速度限制,例如每秒最多 5 个请求
local limit_rate = 5

if limit_count > limit_rate then
ngx.exit(ngx.HTTP_TOO_MANY_REQUESTS)
else
limit_dict:incr(limit_key, 1)
end
}

# 其他处理逻辑...
}
```
kaf
99 天前
http {
# 定义一个 map 块来匹配需要限速的 User-Agent
map $http_user_agent $limited_ua {
default 0; # 默认情况下不进行限速
~*bot 10; # 匹配包含 'bot' 的 User-Agent 并限制为 10 req/s
~*spider 5; # 匹配包含 'spider' 的 User-Agent 并限制为 5 req/s
}

# 在 server 或 location 块中使用 limit_req_zone 指令来定义限速的区域
limit_req_zone $limited_ua zone=ua_limit:10m rate=$limited_ua;

server {
...

location / {
# 在需要限速的 location 块中使用 limit_req 指令来实现限速
limit_req zone=ua_limit burst=5 nodelay;

# 其他配置项
...
}
}
}
knightdf
99 天前
用 ngx-lua module ,想怎么限制都行
wu67
99 天前
@kaf
@dropdatabase 懂了, 感谢.

比较迷惑的是, 如果定义在了 location / 下面, 那么这个 server 下所有的 location 路径都会被限速, 而不是只限制根路径.
我甚至还尝试过开另一个端口启动不限速的服务, 现在改用 map 了.

```
map $http_user_agent $agent_limit_rate {
default 0;
"" 2048k;
~*infuse 2048k;
}

server {
...
limit_rate $agent_limit_rate;
...
}
```
wu67
99 天前
@knightdf 可以的话我还是喜欢少点用其他模块, 尽量用自带的模块完成.

@jinzc 长知识了, openresty 这是 nginx 的二次开发吗? 还是套壳/扩展模块的形式呀?
pipixiadexiapi
99 天前
@wu67 粗浅见解,openresty 是 nginx+lua ,重在 lua 做了许多有用的模块

另外想问问各位大佬,歪个楼,既然已经有了强如 nginx ,openresty ,apisix ,为啥还有公司孜孜不倦 go ,rust 自研网关,我理解网关作为基建没必要做那么重吧
wu67
99 天前
knightdf
99 天前
@wu67 额。。。楼上回复的 openresty 就是用的这个模块,同一个作者
wu67
99 天前
@knightdf 反正我也没装, 我就图省事, 直接 apt install nginx-full
noogler67
98 天前
@pipixiadexiapi 我猜测是因为 nginx+lua 性能是挺高的。但首先人难招,其次 lua 生态差,很多 package 都十年不更新了。是 runtime 特别小的语言,但不是特别完备的语言
pipixiadexiapi
98 天前
@wu67 感谢好文分享。看来还是得够量才能发现问题。我觉得 nginx 强,只是因为没用到瓶颈而已😄

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

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

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

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

© 2021 V2EX