在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;
安裝和啟用UFW:
sudo apt get install ufw
sudo ufw enable
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
配置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
命令來獲取必要的權限。通過以上步驟,你可以顯著提高Nginx服務器的安全性,保護你的網站和應用程序免受潛在的網絡威脅。務必定期審查和更新安全配置,以應對不斷變化的網絡環境。