Ubuntu Nginx如何实现安全防护
小樊
33
2025-12-09 02:37:06
Ubuntu 上 Nginx 的安全防护实践清单
一 系统与网络防护
更新系统与内核,减少已知漏洞面:执行 sudo apt update && sudo apt upgrade -y。
启用 UFW 防火墙,仅开放必要端口:
推荐:sudo ufw allow ‘Nginx Full’(等价于放行 80/443 )
或分别放行:sudo ufw allow 80/tcp;sudo ufw allow 443/tcp
放行 SSH:sudo ufw allow 22/tcp(务必先确保 SSH 可用再启用)
启用:sudo ufw enable;查看状态:sudo ufw status
如需限制管理面,仅允许特定 IP 访问管理端口(示例):sudo ufw allow from to any port 22,443。
建议开启自动安全更新:sudo apt install -y unattended-upgrades && sudo dpkg-reconfigure --priority=low unattended-upgrades。
以上步骤可显著降低暴露面并提升入侵门槛。
二 Nginx 基础加固
隐藏版本信息:在 http 块中添加 server_tokens off;,减少攻击者信息搜集价值。
限制可用 HTTP 方法:在 server 块中添加
if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; }
仅保留业务必需方法,阻断非常规方法滥用。
强化请求与连接超时:
client_body_timeout 12; client_header_timeout 12; keepalive_timeout 15; send_timeout 10;
限制请求速率防滥用:
http { limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s; }
server { location / { limit_req zone=one burst=5 nodelay; } }
安全响应头(降低点击劫持、MIME 嗅探等风险):
add_header X-Frame-Options “SAMEORIGIN”;
add_header X-Content-Type-Options “nosniff”;
禁止访问敏感与隐藏文件:
location ~ /. { deny all; }
这些基础项成本低、收益高,应作为默认配置。
三 加密传输与 HTTPS 部署
使用 Let’s Encrypt 获取并自动配置证书:
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
证书自动续期建议定期执行 dry-run 验证:sudo certbot renew --dry-run。
推荐的 SSL/TLS 配置片段(在 443 端口 server 块中):
listen 443 ssl http2;
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 ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
上述配置兼顾兼容性与安全性,建议全站启用 HTTPS 并开启 HTTP/2 。
四 请求过滤与 WAF 能力
网关层基础特征拦截(示例,按需扩展):
定义匹配变量:set $block_sql_injection 0; set $block_xss 0;
SQL 注入特征:
if ($request_uri ~* “(union|select|insert|update|delete|drop|truncate|or|and|exec|xp_cmdshell)”) { set $block_sql_injection 1; }
if ($args ~* “(union|select|insert|update|delete|drop|truncate|or|and|exec|xp_cmdshell)”) { set $block_sql_injection 1; }
XSS 特征:
if ($request_uri ~* “