以下是在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