以下是在Ubuntu中配置Nginx安全设置的关键步骤,涵盖系统基础加固、Nginx配置及安全防护:
sudo apt update && sudo apt upgrade -y # 更新系统和软件包
sudo apt install unattended-upgrades # 启用自动安全更新
sudo apt autoremove --purge
/etc/ssh/sshd_config
中PermitRootLogin no
,并使用SSH密钥认证。/etc/nginx/nginx.conf
的http
块中添加:server_tokens off; # 隐藏Nginx版本号
# 禁用不需要的模块(如HTTP自动索引)
# 需重新编译Nginx时配置(非默认模块无需操作)
# 仅允许GET/POST/HEAD方法
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 405;
}
# IP白名单示例(拒绝其他IP)
location /admin {
allow 192.168.1.0/24;
deny all;
}
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-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
# 启用HSTS(强制HTTPS)
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com
# 防止点击劫持、XSS等
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Content-Security-Policy "default-src 'self'";
# 限制单个IP请求速率(如100次/分钟)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/m;
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
}
# 限制上传文件大小
client_max_body_size 10M;
sudo apt install libmodsecurity3 libmodsecurity-dev
# 下载Nginx连接器并配置规则(参考ModSecurity官方文档)
access_log /var/log/nginx/access.log combined;
error_log /var/log/nginx/error.log warn;
sudo apt install fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo service fail2ban restart
# 限制配置文件访问权限
sudo chmod 600 /etc/nginx/nginx.conf /etc/nginx/conf.d/*.conf
sudo chown root:root /etc/nginx/ -R
完成配置后,重启Nginx生效:
sudo nginx -t # 测试配置语法
sudo systemctl restart nginx