Nginx在Ubuntu上的安全加固指南
sudo apt update && sudo apt upgrade -y更新所有系统包及Nginx至最新稳定版,修补已知漏洞。sudo ufw default deny incoming # 拒绝所有入站连接
sudo ufw default allow outgoing # 允许所有出站连接
sudo ufw allow OpenSSH # 允许SSH登录(避免被锁)
sudo ufw allow 80/tcp # 允许HTTP(临时,后续强制HTTPS)
sudo ufw allow 443/tcp # 允许HTTPS
sudo ufw enable # 启用防火墙
sudo apt install fail2ban -y
sudo systemctl enable --now fail2ban
/etc/nginx/nginx.conf,在http块中添加:server_tokens off; # 隐藏Nginx版本号
add_header X-Frame-Options "SAMEORIGIN" always; # 防止iframe嵌入
add_header X-Content-Type-Options "nosniff" always; # 禁止内容类型嗅探
add_header X-XSS-Protection "1; mode=block" always; # 启用XSS防护
add_header Referrer-Policy "strict-origin-when-cross-origin" always; # 限制Referer泄露
add_header Permissions-Policy "geolocation=(), microphone=()" always; # 限制权限
http块中定义限流区域,防止单个IP滥用:limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; # 每秒10个请求
在server或location块中应用(如API接口):location /api/ {
limit_req zone=req_limit burst=20 nodelay; # 允许突发20个请求,立即拒绝超限
}
http块中定义共享内存,限制每个IP的并发连接:limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
location / {
limit_conn conn_limit 10; # 每个IP最多10个并发连接
}
}
client_max_body_size 10M; # 限制为10MB
allow/deny指令限制敏感路径访问(如管理后台):location /admin/ {
allow 192.168.1.0/24; # 允许内网IP
allow 10.0.0.0/8; # 允许私有IP
deny all; # 拒绝其他所有IP
}
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 444; # 直接关闭连接(Nginx特有状态码)
}
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com # 替换为你的域名
server块,使用强加密套件并启用HSTS:ssl_protocols TLSv1.2 TLSv1.3; # 仅使用TLS 1.2及以上
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256'; # 强加密套件
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always; # 强制HTTPS
http块中定义日志格式,记录客户端IP、请求方法、状态码等信息: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;
grep、awk等工具分析日志,查找异常请求(如大量404、403错误):sudo grep " 404 " /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr # 统计404错误的IP
sudo apt install unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades
sudo tar -czvf nginx-backup-$(date +%F).tar.gz /etc/nginx /var/log/nginx
nginx -t检查语法,避免配置错误导致服务中断:sudo nginx -t
sudo systemctl reload nginx # 重新加载配置(不重启服务)
通过以上步骤,可显著提升Ubuntu上Nginx的安全性,防范常见攻击(如版本探测、DDoS、SQL注入、XSS等)。安全是持续过程,需定期审查配置并根据业务需求调整。