Nginx可以通过多种方式实现防火墙功能,以下是几种常见的设置方法:
location / {
# 允许特定IP
allow 192.168.1.1;
allow 192.168.1.2;
# 拒绝所有其他IP
deny all;
# 其他配置...
}
server {
if ($http_user_agent ~* (wget|curl|httrack|nikto|sqlmap)) {
return 403;
}
# 其他配置...
}
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=20 nodelay;
# 其他配置...
}
}
}
安装ModSecurity:
# Ubuntu/Debian
sudo apt-get install libmodsecurity3 modsecurity-crs nginx-module-modsecurity
# CentOS/RHEL
sudo yum install mod_security mod_security_crs
在nginx.conf中启用:
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
配置规则集(OWASP CRS)
http {
geo $blocked_ip {
default 0;
1.2.3.4 1; # 黑名单IP
5.6.7.8 1; # 黑名单IP
}
server {
if ($blocked_ip) {
return 403;
}
# 其他配置...
}
}
location / {
if ($args ~* "union.*select.*\(") {
return 403;
}
if ($args ~* "concat.*\(") {
return 403;
}
# 其他配置...
}
location / {
if ($args ~* "<script>") {
return 403;
}
# 其他配置...
}
安装fail2ban:
sudo apt-get install fail2ban
创建Nginx过滤器:
# /etc/fail2ban/filter.d/nginx-noscript.conf
[Definition]
failregex = ^<HOST> -.*GET.*(\.php|\.asp|\.exe|\.pl|\.cgi|\.scgi)
配置jail:
[nginx-noscript]
enabled = true
port = http,https
filter = nginx-noscript
logpath = /var/log/nginx/access.log
maxretry = 6
server_tokens off;
client_max_body_size 10m;
根据您的具体需求和安全级别,可以选择以上一种或多种方法组合使用。