作为一款高性能的Web服务器和反向代理,Nginx的安全性至关重要。以下是针对Nginx安全问题的全面解决方案:
nginx
server_tokens off; # 隐藏Nginx版本信息
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
nginx
client_body_buffer_size 1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
nginx
merge_slashes on;
nginx
# 确保URL编码正确
rewrite ^/(.*) http://example.com/$1 permanent;
user nginx;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
}
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
ssl_ecdh_curve secp384r1;
ssl_session_timeout 10m;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
location /admin {
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
}
location = /favicon.ico { access_log off; log_not_found off; }
location ~ /\. { deny all; access_log off; log_not_found off; }
定期更新:
# Ubuntu/Debian
sudo apt-get update && sudo apt-get upgrade nginx
# CentOS/RHEL
sudo yum update nginx
日志监控:
WAF集成:
定期安全扫描:
location / {
limit_except GET POST {
deny all;
}
}
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=5;
}
}
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.example.com; img-src 'self' https://*.example.com; style-src 'self' 'unsafe-inline'";
通过以上措施,您可以显著提高Nginx服务器的安全性,减少被攻击的风险。建议定期审查和更新安全配置,以适应不断变化的威胁环境。