作为高性能的Web服务器和反向代理,Nginx需要在性能和安全之间找到平衡点。以下是我总结的关键策略:
# 禁用server tokens
server_tokens off;
# 限制HTTP方法
limit_except GET POST { deny all; }
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN";
# 启用XSS保护
add_header X-XSS-Protection "1; mode=block";
# 内容安全策略
add_header Content-Security-Policy "default-src 'self'";
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;
worker_processes auto;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
}
keepalive_timeout 30;
keepalive_requests 100;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
安全与缓存的平衡:
add_header Cache-Control "no-store, no-cache, must-revalidate";
请求限制:
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
location / {
limit_req zone=one burst=20 nodelay;
}
资源限制:
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 8k;
日志平衡:
error_log /var/log/nginx/error.log warn;
模块选择:
ngx_http_stub_status_module
监控性能指标nginx -t
和第三方扫描工具通过以上策略,可以在不显著影响性能的前提下大幅提升Nginx的安全性。实际配置应根据具体业务需求、流量模式和威胁模型进行调整。