插件窝 干货文章 Nginx如何实现安全性配置

Nginx如何实现安全性配置

Nginx 安全 配置 SSL 648    来源:    2025-04-10

Nginx安全性配置指南

Nginx作为广泛使用的Web服务器和反向代理,合理的安全配置至关重要。以下是提升Nginx安全性的关键配置方案:

1. 基础安全配置

禁用服务器令牌

server_tokens off;

隐藏Nginx版本信息,防止攻击者利用特定版本漏洞。

限制HTTP方法

if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}

只允许必要的HTTP方法(GET, HEAD, POST)。

禁用自动目录列表

autoindex off;

防止目录遍历攻击。

2. SSL/TLS安全配置

强制HTTPS

server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

安全SSL配置

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

3. 请求限制

限制请求大小

client_max_body_size 1m;
client_body_buffer_size 1m;

限制请求速率

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

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

4. 头部安全配置

安全相关HTTP头

add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy "default-src 'self';";
add_header Referrer-Policy "strict-origin-when-cross-origin";

5. 访问控制

IP访问限制

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

基本认证

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

6. 文件权限和安全

确保Nginx运行在专用用户下:

user nginx;

配置文件权限:

chown -R root:nginx /etc/nginx/
chmod -R 750 /etc/nginx/

7. 日志与监控

access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;

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

8. 防止常见攻击

SQL注入防护

location ~* "union.*select.*\(" {
    deny all;
}

XSS防护

location ~* "<script.*>.*</script>" {
    deny all;
}

9. 定期维护

  • 保持Nginx更新到最新稳定版本
  • 定期检查日志文件
  • 使用安全扫描工具(如Nessus, OpenVAS)定期扫描
  • 实施WAF(Web应用防火墙)如ModSecurity

以上配置应根据实际业务需求进行调整,并在实施前进行充分测试。安全是一个持续的过程,需要定期审查和更新安全策略。