Nginx Lua 代码:仅允许特定 User Agent 访问
以下是一个示例的 Nginx 配置代码,仅允许带有'qyuc'的 User Agent 才能访问:
http {
lua_shared_dict ua_dict 10m;
init_by_lua_block {
local ua_dict = ngx.shared.ua_dict
ua_dict:set('qyuc', true)
}
server {
listen 80;
server_name example.com;
location / {
access_by_lua_block {
local ua_dict = ngx.shared.ua_dict
local ua = ngx.var.http_user_agent
if not ua_dict:get(ua) then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
}
...
# Your regular location configuration goes here
...
}
}
}
这段代码包含了一个lua_shared_dict,用于存储允许访问的 User Agent 信息。在init_by_lua_block中,我们将'qyuc'添加到字典中。在access_by_lua_block中,我们获取了 User Agent 并检查它是否在字典中。如果不是,则返回 HTTP 403 Forbidden 错误。
这段代码应该放在你的 Nginx 配置文件中的http块中,可以在server块中的任何位置使用。建议将它放在你的主服务器块中,以确保所有虚拟主机都受到保护。
原文地址: https://www.cveoy.top/t/topic/nwCR 著作权归作者所有。请勿转载和采集!