在Debian上安全運行Nginx涉及多個步驟,包括安裝、配置、啟用服務、設置防火墻規則以及啟用HTTPS。以下是詳細的步驟指南:
首先,確保你的Debian系統是最新的:
sudo apt update
sudo apt upgrade -y
然后,安裝Nginx:
sudo apt install nginx -y
安裝完成后,啟動Nginx并設置開機自啟動:
sudo systemctl start nginx
sudo systemctl enable nginx
編輯Nginx的默認站點配置文件:
sudo nano /etc/nginx/sites-available/default
找到以下部分并進行修改:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.php index.html index.htm index.nginx-debian.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}
location ~ /\.ht {
deny all;
}
}
保存并退出編輯器,然后測試Nginx配置:
sudo nginx -t
重新加載Nginx以應用更改:
sudo systemctl reload nginx
安裝并啟用UFW(Uncomplicated Firewall):
sudo apt install ufw
sudo ufw enable
允許HTTP和HTTPS流量:
sudo ufw allow 'Nginx Full'
或者手動允許特定端口:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
重新加載UFW以使更改生效:
sudo ufw reload
配置SSL證書并強制HTTPS訪問。你可以使用Let’s Encrypt免費獲取SSL證書:
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com
按照提示完成證書的安裝和配置。
編輯Nginx配置文件(通常位于 /etc/nginx/nginx.conf
或 /etc/nginx/sites-available/default
),添加或修改以下配置:
server {
listen 443 ssl;
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:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
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";
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
重啟Nginx以應用更改:
sudo systemctl reload nginx
保持系統和軟件包的最新狀態,以修補已知的安全漏洞:
sudo apt update && sudo apt upgrade
通過以上步驟,你可以在Debian上安全地運行Nginx,并確保其具有良好的安全性和性能。