作为一款高性能的Web服务器和反向代理,Nginx在生产环境中的安全配置至关重要。以下是一套全面的Nginx安全实践方案:
server_tokens off;
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 405;
}
# 禁用自动目录列表
autoindex off;
# 禁用SSI(服务器端包含)
ssi off;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305...';
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=20 nodelay;
}
}
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'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com;";
add_header Referrer-Policy "no-referrer-when-downgrade";
add_header Permissions-Policy "geolocation=(), midi=(), camera=()";
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;
error_log /var/log/nginx/error.log warn;
user nginx;
chmod 640 /etc/nginx/conf.d/*.conf
chown root:nginx /etc/nginx/conf.d/*.conf
location ~* "(\'|\")(.*)(drop|insert|md5|select|union)" {
deny all;
}
location ~* \.(?:php|pl|cgi|sh)$ {
deny all;
}
add_header X-Frame-Options "SAMEORIGIN";
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
# /etc/fail2ban/jail.d/nginx.conf
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
通过实施这些安全措施,可以显著提高Nginx在生产环境中的安全性。根据具体业务需求,可能还需要调整或添加其他安全配置。