零基础从头教学Linux(Day 46)
Nginx黑白名单
基于 IP 的黑白名单配置指南
一、白名单配置(仅允许特定 IP 访问)
方法一:使用 allow/deny 指令(Nginx 0.7.64+)
server {listen 80;server_name example.com;location / {allow 192.168.1.100; # 允许指定IP访问deny all; # 拒绝其他所有IProot /usr/share/nginx/html;index index.html index.htm;}
}
方法二:使用 geo 模块(推荐)
# 定义允许访问的IP列表
geo $allowed {default 0; # 默认拒绝访问192.168.1.100 1; # 允许访问的IP192.168.1.101 1;
}server {listen 80;server_name example.com;location / {if ($allowed = 0) {return 403;}root /usr/share/nginx/html;index index.html index.htm;}
}
二、黑名单配置(禁止特定 IP 访问)
方法一:使用 deny 指令
server {listen 80;server_name example.com;location / {deny 192.168.1.100; # 禁止指定IP访问root /usr/share/nginx/html;index index.html index.htm;}
}
方法二:使用 map 模块(推荐)
# 定义禁止访问的IP列表
map $remote_addr $blocked {"192.168.1.100" 1; # 禁止访问的IPdefault 0;
}server {listen 80;server_name example.com;location / {if ($blocked = 1) {return 403;}root /usr/share/nginx/html;index index.html index.htm;}
}
三、基于 User-Agent 的黑白名单
白名单配置(仅允许特定浏览器)
# 定义允许的User-Agent
map $http_user_agent $allowed_agent {"~*(Chrome|Firefox)" 1; # 允许Chrome和Firefoxdefault 0;
}server {listen 80;server_name example.com;location / {if ($allowed_agent = 0) {return 403;}root /usr/share/nginx/html;index index.html index.htm;}
}
黑名单配置(禁止特定爬虫)
# 定义禁止的User-Agent
map $http_user_agent $blocked_agent {"~*BadBot" 1; # 禁止BadBot访问default 0;
}server {listen 80;server_name example.com;location / {if ($blocked_agent = 1) {return 403;}root /usr/share/nginx/html;index index.html index.htm;}
}
配置注意事项
配置文件位置:
- 主配置:
/etc/nginx/nginx.conf
- 虚拟主机配置:
/etc/nginx/conf.d/
或/etc/nginx/sites-available/
- 主配置:
模块支持:
- 使用前确认已编译所需模块(geo/map)
- 可通过
nginx -V
查看已安装模块
配置生效:
- 修改后执行
nginx -t
检查语法 - 使用
nginx -s reload
重载配置
- 修改后执行