# 隐藏Nginx版本信息
server_tokens off;
# 限制HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 禁用不必要的HTTP头
more_clear_headers 'Server';
more_clear_headers 'X-Powered-By';
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
# 限制请求体大小
client_max_body_size 10m;
# 限制缓冲区大小
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
# 限制连接速率
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
limit_req zone=req_limit burst=20 nodelay;
}
# IP黑白名单
allow 192.168.1.0/24;
deny all;
# 基于地理位置限制
geo $blocked_country {
default 0;
include /etc/nginx/conf.d/geo_block.conf;
}
server {
if ($blocked_country) {
return 403;
}
}
upstream backend {
# 使用最少连接算法
least_conn;
# 配置健康检查
server backend1.example.com max_fails=3 fail_timeout=30s;
server backend2.example.com max_fails=3 fail_timeout=30s;
server backend3.example.com max_fails=3 fail_timeout=30s;
# 保持连接数
keepalive 32;
}
# 使用SSL与后端通信
proxy_ssl_verify on;
proxy_ssl_trusted_certificate /path/to/trusted_ca.crt;
proxy_ssl_verify_depth 2;
proxy_ssl_session_reuse on;
# 设置适当的超时
proxy_connect_timeout 5s;
proxy_send_timeout 10s;
proxy_read_timeout 30s;
# 限制连接数
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
limit_conn conn_limit 20;
}
# 速率限制特定URL
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/m;
location /api/ {
limit_req zone=api_limit burst=200 nodelay;
}
# ModSecurity集成示例
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
# 或者使用NAXSI
location / {
# 启用NAXSI核心规则
SecRulesEnabled;
# 学习模式(生产环境应关闭)
LearningMode;
# 拒绝规则
DeniedUrl "/RequestDenied";
# 检查规则
CheckRule "$SQL >= 8" BLOCK;
CheckRule "$RFI >= 8" BLOCK;
CheckRule "$TRAVERSAL >= 4" BLOCK;
CheckRule "$EVADE >= 4" BLOCK;
CheckRule "$XSS >= 8" BLOCK;
}
定期更新:保持Nginx和所有模块更新到最新稳定版本
最小权限原则:
chown -R nginx:nginx /var/log/nginx
chmod -R 750 /var/log/nginx
日志监控:
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;
文件权限限制:
location ~* \.(htaccess|htpasswd|ini|log|sh|cfg|inc|bak|swp)$ {
deny all;
}
location ~ /\. {
deny all;
}
HTTP安全头:
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self';";
add_header Referrer-Policy "strict-origin-when-cross-origin";
定期审计:
nginx -t
测试配置通过实施这些安全措施,无论是单机还是负载均衡环境下的Nginx反向代理,都能显著提高系统的安全性,抵御常见的网络攻击。