插件窝 干货文章 Nginx中的HTTP访问控制与常见安全漏洞

Nginx中的HTTP访问控制与常见安全漏洞

Nginx location 防护 请求 361    来源:    2025-04-20

Nginx HTTP访问控制与安全漏洞防护指南

一、Nginx HTTP访问控制基础

1. 基于IP的访问控制

location /admin/ {
    allow 192.168.1.0/24;
    allow 10.0.0.1;
    deny all;
}

2. 基于密码的认证

location /secure/ {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

3. 基于HTTP方法的限制

location /api/ {
    limit_except GET POST {
        deny all;
    }
}

二、常见安全漏洞及防护措施

1. 目录遍历漏洞

防护措施

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

location / {
    autoindex off;
}

2. HTTP请求走私

防护措施

server {
    # 确保每个请求只解析一个请求头
    http2_max_requests 1;

    # 禁用分块传输编码
    chunked_transfer_encoding off;
}

3. CRLF注入

防护措施

server {
    # 严格检查请求头
    underscores_in_headers off;

    # 禁用非标准请求头
    ignore_invalid_headers on;
}

4. 慢速攻击

防护措施

server {
    # 设置连接超时
    client_body_timeout 10s;
    client_header_timeout 10s;

    # 限制请求体大小
    client_max_body_size 1m;

    # 限制请求速率
    limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
}

5. XSS防护

add_header X-XSS-Protection "1; mode=block";

6. 点击劫持防护

add_header X-Frame-Options "SAMEORIGIN";

7. 内容嗅探防护

add_header X-Content-Type-Options "nosniff";

三、高级安全配置

1. SSL/TLS最佳实践

server {
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_stapling on;
    ssl_stapling_verify on;
}

2. 隐藏服务器信息

server_tokens off;
more_clear_headers Server;

3. 限制敏感文件访问

location ~ /\.(ht|git|svn) {
    deny all;
}

location ~* \.(ini|conf|env|log)$ {
    deny all;
}

4. 防止信息泄露

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

四、监控与日志分析

1. 安全日志配置

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

access_log /var/log/nginx/security.log security;

2. 可疑请求监控

map $request_uri $is_suspicious {
    default 0;
    ~*\.php 1;
    ~*\.asp 1;
    ~*\.jsp 1;
    ~*\.exe 1;
    ~*\.sh  1;
}

server {
    if ($is_suspicious) {
        access_log /var/log/nginx/suspicious.log security;
    }
}

五、定期安全审计建议

  1. 使用nginx -t测试配置语法
  2. 定期检查Nginx漏洞公告(CVE)
  3. 使用工具如Nessus、OpenVAS进行扫描
  4. 定期审计访问日志
  5. 保持Nginx版本更新

通过实施这些访问控制和安全措施,可以显著提高Nginx服务器的安全性,防范常见Web攻击。