作为IT工程师,确保Nginx服务器的安全性至关重要。以下是一份全面的Nginx安全配置指南,帮助您防范各种网络攻击和恶意访问。
server_tokens off;
location / {
limit_except GET POST {
deny all;
}
}
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_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_session_tickets off;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
server {
listen 80 default_server;
server_name _;
return 444;
}
client_body_buffer_size 1k;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=5;
}
}
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location / {
limit_conn addr 10;
}
}
client_body_timeout 10s;
client_header_timeout 10s;
keepalive_timeout 5s 5s;
send_timeout 10s;
location /login {
limit_req zone=login_limit burst=3 nodelay;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}
autoindex off;
location ~ /\.ht {
deny all;
}
location ~* \.(ini|log|conf|sql)$ {
deny all;
}
location /admin/ {
allow 192.168.1.0/24;
deny all;
}
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
listen 443 ssl http2;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' cdn.example.com;";
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/security.log security;
# 使用fail2ban监控Nginx日志
sudo apt install fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
通过实施这些安全措施,您可以显著提高Nginx服务器的安全性,防范大多数常见的网络攻击和恶意访问。根据您的具体需求,可能需要调整某些配置参数。