Nginx Lua 限制 User-Agent 访问:仅允许包含 'qyuc' 的 UA
以下是一个基本的 nginx 配置文件,它仅允许带有 'qyuc' 的 User-Agent 访问:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
# 只允许带有 'qyuc' 的 User-Agent 访问
map $http_user_agent $qyuc {
default 0;
~qyuc 1;
}
# 定义一个 Lua 函数,用于检查 User-Agent
# 如果不符合要求,则返回 403 状态码
# 如果符合要求,则继续执行后续操作
lua_shared_dict ua_dict 1m;
lua_package_path "/usr/local/btwaf/conf/?.lua;;";
init_by_lua_block {
local dict = ngx.shared.ua_dict
dict:set("qyuc", true)
}
access_by_lua_block {
local dict = ngx.shared.ua_dict
local qyuc = dict:get("qyuc")
if qyuc and ngx.var.http_user_agent ~= nil and ngx.re.match(ngx.var.http_user_agent, "qyuc") then
return
end
ngx.exit(ngx.HTTP_FORBIDDEN)
}
# 定义一个 server 块,监听 80 端口
server {
listen 80;
server_name localhost;
# 定义一个 location 块,用于处理请求
location / {
root html;
index index.html index.htm;
}
}
}
你可以将上述代码放置在宝塔面板的 nginx 配置文件中,路径为 /www/server/panel/vhost/nginx/你的网站域名.conf。请注意,如果你的网站使用 HTTPS,你需要在上面的代码中添加 SSL 相关的配置。另外,如果你的网站已经存在其他的 nginx 配置文件,你需要将上述代码合并到现有的配置文件中,而不是创建一个新的文件。
原文地址: https://www.cveoy.top/t/topic/nwCU 著作权归作者所有。请勿转载和采集!