插件窝 干货文章 Nginx安全配置指南,防止网站攻击和恶意访问

Nginx安全配置指南,防止网站攻击和恶意访问

Nginx 配置 防止 攻击 177    来源:    2025-04-16

Nginx安全配置指南:防止网站攻击和恶意访问

作为IT工程师,确保Nginx服务器的安全性至关重要。以下是一份全面的Nginx安全配置指南,帮助您防范各种网络攻击和恶意访问。

1. 基础安全配置

1.1 隐藏Nginx版本信息

server_tokens off;

1.2 禁用不需要的HTTP方法

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

1.3 配置安全的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;

2. 防止常见攻击

2.1 防止点击劫持

add_header X-Frame-Options "SAMEORIGIN";

2.2 防止XSS攻击

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

2.3 防止MIME类型混淆攻击

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

2.4 防止HTTP Host头攻击

server {
    listen 80 default_server;
    server_name _;
    return 444;
}

3. 限制和访问控制

3.1 限制请求大小和缓冲区

client_body_buffer_size 1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;

3.2 限制连接速率

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

server {
    location / {
        limit_req zone=one burst=5;
    }
}

3.3 限制并发连接数

limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    location / {
        limit_conn addr 10;
    }
}

4. 防止DDoS和暴力破解

4.1 防止慢速攻击

client_body_timeout 10s;
client_header_timeout 10s;
keepalive_timeout 5s 5s;
send_timeout 10s;

4.2 防止暴力破解登录

location /login {
    limit_req zone=login_limit burst=3 nodelay;
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

5. 文件和目录安全

5.1 禁用目录列表

autoindex off;

5.2 保护敏感文件

location ~ /\.ht {
    deny all;
}

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

5.3 限制访问特定目录

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

6. 高级安全配置

6.1 使用ModSecurity WAF

load_module modules/ngx_http_modsecurity_module.so;

http {
    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;
}

6.2 启用HTTP/2

listen 443 ssl http2;

6.3 配置CSP策略

add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' cdn.example.com;";

7. 日志和监控

7.1 详细日志记录

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

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

7.2 实时监控配置

# 使用fail2ban监控Nginx日志
sudo apt install fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

8. 定期维护

  1. 保持Nginx更新:定期检查并安装最新安全补丁
  2. 审计配置:定期检查Nginx配置是否有安全漏洞
  3. 监控日志:设置警报机制监控异常访问模式
  4. 备份配置:定期备份Nginx配置文件

通过实施这些安全措施,您可以显著提高Nginx服务器的安全性,防范大多数常见的网络攻击和恶意访问。根据您的具体需求,可能需要调整某些配置参数。