CentOS 下 Nginx 安全设置指南
一 基础加固
sudo yum update -yuser nobody;(在 /etc/nginx/nginx.conf 的顶层配置)server_tokens off;autoindex off;(或编译期不启用 autoindex 模块)proxy_hide_header X-Powered-By; proxy_hide_header Server;location /admin {
allow 192.168.1.0/24;
deny all;
}
log_format main '$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/access.log main;
error_log /var/log/nginx/error.log warn;
以上措施能显著降低信息泄露与滥用风险,并提升可运维性与可观测性。
二 传输加密与 HTTPS
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
sudo yum install -y epel-release
sudo yum install -y certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
}
三 请求限制与资源防护
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
location / {
limit_req zone=one burst=5 nodelay;
}
}
}
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
client_max_body_size 10m;(按业务调整)if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 444; # 直接关闭连接
}
location ~* ^/(uploads|templets|data)/.*\.(php|php5)$ {
return 444;
}
四 安全响应头与内容防护
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trustedscripts.example.com; object-src 'none';" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
五 运维与持续安全
sudo nginx -t
sudo systemctl reload nginx
sudo systemctl enable --now nginx
sudo systemctl status nginx
sudo yum install -y fail2ban
sudo systemctl enable --now fail2ban