在Debian系统下配置Nginx的安全性是一个重要的步骤,可以有效地保护你的Web服务不受各种网络威胁。以下是一个详细的Nginx安全设置指南:
隐藏版本号信息:
编辑Nginx配置文件(通常位于 /etc/nginx/nginx.conf 或 /usr/local/nginx/conf/nginx.conf),在 http 块中添加 server_tokens off; 以关闭版本信息显示。
配置安全HTTP响应头:
添加以下指令来增强安全性:
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1;mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Referrer-Policy "strict-origin-when-cross-origin";
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'";
限制连接数和请求频率:
在 http 块中定义共享内存区域和限制:
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn addr 100;
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=10r/s burst=20;
limit_req zone=req_zone burst=20 nodelay;
配置白名单:
例如,限制管理后台的访问:
location /admin/ {
    allow 192.168.1.0/24;
    allow 10.0.0.0/8;
    deny all;
    auth_basic "Restricted Access";
    auth_basic_user_file /etc/nginx/.htpasswd;
}
启用HTTPS配置:
配置SSL证书并强制HTTPS访问:
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
if ($scheme != "https") {
    return 301 https://$server_name$request_uri;
}
add_header Strict-Transport-Security "max-age=31536000" always;
优化SSL配置:
使用更安全的SSL配置参数:
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
防火墙配置:
安装和启用UFW:
sudo apt-get install ufw
sudo ufw enable
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
配置iptables规则(更底层):
安装iptables:
sudo apt-get install iptables
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT # 允许SSH
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT # 允许HTTP
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT # 允许HTTPS
sudo iptables-save /etc/iptables/rules.v4
sudo systemctl restart iptables
其他安全建议:
定期更新系统和软件:
保持系统和软件包的最新状态,以修补已知的安全漏洞:
sudo apt update && sudo apt upgrade
使用强密码策略:
通过PAM模块设置密码复杂度要求,增强账户安全性。
限制root用户的使用:
避免直接使用root用户进行操作,使用 sudo 命令来获取必要的权限。
监控和日志管理:
启用和配置日志记录功能,定期检查日志文件以发现异常行为。