插件窝 干货文章 Nginx如何防范API接口攻击

Nginx如何防范API接口攻击

Nginx 配置 limit API 489    来源:    2025-04-20

Nginx防范API接口攻击的综合方案

作为IT工程师,我可以提供一套全面的Nginx配置方案来防范API接口攻击。以下是具体实施方法:

1. 基础安全配置

1.1 限制HTTP方法

location /api/ {
    if ($request_method !~ ^(GET|POST|PUT|DELETE)$ ) {
        return 405;
    }
    # 其他配置...
}

1.2 隐藏Nginx版本信息

server_tokens off;

1.3 禁用不需要的HTTP方法

add_header Allow "GET, POST, PUT, DELETE" always;
if ($request_method !~ ^(GET|POST|PUT|DELETE)$ ) {
    return 405;
}

2. 速率限制

2.1 全局速率限制

limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;

location /api/ {
    limit_req zone=api_limit burst=200 nodelay;
    # 其他配置...
}

2.2 针对特定API的速率限制

limit_req_zone $binary_remote_addr zone=login_limit:10m rate=5r/m;

location /api/login {
    limit_req zone=login_limit burst=5 nodelay;
    # 其他配置...
}

3. 防DDoS攻击

3.1 连接数限制

limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    limit_conn addr 10;
    # 其他配置...
}

3.2 启用SYN Cookie

syn_flood on;

4. 防SQL注入和XSS攻击

4.1 过滤恶意请求

set $block 0;
if ($query_string ~* "union.*select.*\(") {
    set $block 1;
}
if ($query_string ~* "concat.*\(") {
    set $block 1;
}
if ($block = 1) {
    return 403;
}

4.2 防止目录遍历

location ~* \.(php|asp|jsp|pl)$ {
    deny all;
}

5. 高级防护措施

5.1 启用WAF (Web应用防火墙)

# 使用ModSecurity等WAF模块
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;

5.2 IP黑白名单

location /api/ {
    allow 192.168.1.0/24;
    allow 10.0.0.1;
    deny all;
    # 其他配置...
}

5.3 请求验证

location /api/ {
    # 验证Content-Type
    if ($content_type !~ "application/json") {
        return 415;
    }

    # 验证User-Agent
    if ($http_user_agent ~* "(wget|curl|python|java|php)") {
        return 403;
    }
}

6. 日志与监控

6.1 详细日志记录

log_format api_log '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent" '
                   '$request_time $upstream_response_time';

access_log /var/log/nginx/api_access.log api_log;

6.2 异常请求监控

map $status $loggable {
    ~^[23]  0;
    default 1;
}

access_log /var/log/nginx/api_errors.log combined if=$loggable;

7. SSL/TLS安全配置

ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;

8. 定期维护建议

  1. 定期更新Nginx到最新稳定版本
  2. 审查和更新安全规则
  3. 监控日志中的异常模式
  4. 定期进行安全扫描和渗透测试

以上配置需要根据实际业务需求进行调整,建议在测试环境验证后再部署到生产环境。