插件窝 干货文章 nginx防火墙怎么设置

nginx防火墙怎么设置

Nginx ModSecurity 配置 使用 117    来源:    2025-04-07

Nginx防火墙设置指南

Nginx可以通过多种方式实现防火墙功能,以下是几种常见的设置方法:

1. 使用Nginx内置的访问控制

基本IP限制

location / {
    # 允许特定IP
    allow 192.168.1.1;
    allow 192.168.1.2;

    # 拒绝所有其他IP
    deny all;

    # 其他配置...
}

基于User-Agent的过滤

server {
    if ($http_user_agent ~* (wget|curl|httrack|nikto|sqlmap)) {
        return 403;
    }
    # 其他配置...
}

2. 使用Nginx的limit_req模块防止DDoS

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

    server {
        location / {
            limit_req zone=one burst=20 nodelay;
            # 其他配置...
        }
    }
}

3. 使用ModSecurity WAF (Web应用防火墙)

  1. 安装ModSecurity:

    # Ubuntu/Debian
    sudo apt-get install libmodsecurity3 modsecurity-crs nginx-module-modsecurity
    
    # CentOS/RHEL
    sudo yum install mod_security mod_security_crs
    
  2. 在nginx.conf中启用:

    load_module modules/ngx_http_modsecurity_module.so;
    
    http {
       modsecurity on;
       modsecurity_rules_file /etc/nginx/modsec/main.conf;
    }
    
  3. 配置规则集(OWASP CRS)

4. 使用Nginx的geo模块创建IP黑名单

http {
    geo $blocked_ip {
        default 0;
        1.2.3.4 1;  # 黑名单IP
        5.6.7.8 1;  # 黑名单IP
    }

    server {
        if ($blocked_ip) {
            return 403;
        }
        # 其他配置...
    }
}

5. 防止常见攻击

SQL注入防护

location / {
    if ($args ~* "union.*select.*\(") {
        return 403;
    }
    if ($args ~* "concat.*\(") {
        return 403;
    }
    # 其他配置...
}

XSS防护

location / {
    if ($args ~* "<script>") {
        return 403;
    }
    # 其他配置...
}

6. 使用fail2ban与Nginx配合

  1. 安装fail2ban:

    sudo apt-get install fail2ban
    
  2. 创建Nginx过滤器:

    # /etc/fail2ban/filter.d/nginx-noscript.conf
    [Definition]
    failregex = ^<HOST> -.*GET.*(\.php|\.asp|\.exe|\.pl|\.cgi|\.scgi)
    
  3. 配置jail:

    [nginx-noscript]
    enabled  = true
    port     = http,https
    filter   = nginx-noscript
    logpath  = /var/log/nginx/access.log
    maxretry = 6
    

最佳实践建议

  1. 定期更新Nginx和防火墙规则
  2. 只开放必要的端口和服务
  3. 使用HTTPS加密所有流量
  4. 限制HTTP方法(GET/POST)
  5. 隐藏Nginx版本信息: server_tokens off;
  6. 设置适当的请求大小限制: client_max_body_size 10m;

根据您的具体需求和安全级别,可以选择以上一种或多种方法组合使用。