作为IT工程师,以下是针对Nginx反向代理的安全和性能优化建议:
server_tokens off; # 隐藏Nginx版本信息
add_header X-Frame-Options "SAMEORIGIN"; # 防止点击劫持
add_header X-XSS-Protection "1; mode=block"; # 防止XSS攻击
add_header X-Content-Type-Options "nosniff"; # 防止MIME类型混淆
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; # OCSP装订
location /admin {
allow 192.168.1.0/24; # 限制特定IP访问
deny all;
auth_basic "Restricted Content"; # 基本认证
auth_basic_user_file /etc/nginx/.htpasswd;
}
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; # 请求速率限制
server {
limit_req zone=one burst=20 nodelay; # 应用限制
}
proxy_buffering on;
proxy_buffer_size 8k;
proxy_buffers 8 32k;
proxy_busy_buffers_size 64k;
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 10m;
keepalive_timeout 65;
keepalive_requests 100;
client_header_timeout 10;
client_body_timeout 10;
send_timeout 10;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com;
server backup.example.com backup;
keepalive 32; # 保持连接池
}
# 使用ModSecurity模块
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
geo $bad_ips {
default 0;
include /etc/nginx/conf.d/blacklist.conf;
}
server {
if ($bad_ips) {
return 403;
}
}
# 防止SQL注入和路径遍历
if ($query_string ~* "union.*select.*\(") {
return 403;
}
if ($request_uri ~* "\.\./") {
return 403;
}
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/security.log security;
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
实施这些优化后,建议: 1. 定期进行安全扫描和渗透测试 2. 监控Nginx错误日志和访问模式 3. 保持Nginx和系统更新到最新版本 4. 定期审查和调整配置参数
这些措施将显著提升您的Nginx反向代理的安全性和性能。