零基础新手小白快速了解掌握服务集群与自动化运维(十)Nginx模块--Nginx黑白名单
一、基于 IP 的黑白名单
白名单(只允许特定 IP 访问,仅允许)
编辑 Nginx 配置文件
通常在
/etc/nginx/nginx.conf
或/etc/nginx/conf.d/
下的虚拟主机配置文件中添加以下内容。
使用 allow 和 deny 指令(Nginx 0.7.64 及以上版本)
server {listen 80;server_name example.com;location / {allow 192.168.1.100; # 允许这个IP访问deny all; # 拒绝其他所有IP访问root /usr/share/nginx/html;index index.html index.htm;}
}
使用 geo 模块(推荐,更灵活)
在
http
块内添加:
# 创建一个名为 $allowed 的 geo 变量块
geo $allowed {# 设置默认值为 0,表示不允许访问default 0;# 当客户端 IP 为 192.168.1.100 时,将 $allowed 变量的值设置为 1,表示允许该 IP 访问192.168.1.100 1;192.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 模块(更灵活)
在
http
块内添加:
# 创建一个名为 $blocked 的 map 变量,其值根据客户端的 IP 地址($remote_addr)来确定
map $remote_addr $blocked {# 当客户端的 IP 地址为 192.168.1.100 时,将 $blocked 变量的值设置为 1"192.168.1.100" 1;# 对于其他所有未在上述规则中明确匹配的 IP 地址,将 $blocked 变量的值设置为 0default 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)的黑白名单
白名单(只允许特定用户代理访问)
使用 if 指令(不推荐,if 有性能问题,但简单场景可用)
server {listen 80;server_name example.com;location / {if ($http_user_agent !~* "Chrome|Firefox") {return 403;}root /usr/share/nginx/html;index index.html index.htm;}
}
使用 map 模块(推荐)
在
http
块内添加:
# 创建一个名为 $allowed_agent 的 map 变量,其值根据客户端的用户代理($http_user_agent)来确定
map $http_user_agent $allowed_agent {# 使用正则表达式匹配,如果用户代理字符串中包含 Chrome 或 Firefox(不区分大小写),则将 $allowed_agent 变量的值设置为 1"~*(Chrome|Firefox)" 1;# 对于其他所有未匹配上述正则表达式的用户代理,将 $allowed_agent 变量的值设置为 0default 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;}
}
黑名单(禁止特定用户代理访问)
使用 if 指令
server {listen 80;server_name example.com;location / {if ($http_user_agent ~* "BadBot") {return 403;}root /usr/share/nginx/html;index index.html index.htm;}
}
使用 map 模块
在
http
块内添加:
map $http_user_agent $blocked_agent {"~*BadBot" 1;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;}
}
注意事项
配置文件位置
Nginx 的主配置文件通常在
/etc/nginx/nginx.conf
,虚拟主机配置文件可能在/etc/nginx/conf.d/
或/etc/nginx/sites - available/
等目录下。
模块支持
确保 Nginx 编译时包含了需要的模块(如
geo
、map
模块等)。如果不确定,可以查看nginx -V
的输出。
语法检查和重载
修改配置文件后,可以使用
nginx -t
检查语法是否正确,然后使用nginx -s reload
重新加载配置。