服务器设置和教程 · 9 10 月, 2024

在 Ubuntu 18.04 上使用 Let’s Encrypt 保護 Nginx

在 Ubuntu 18.04 上使用 Let’s Encrypt 保護 Nginx

隨著網絡安全的重要性日益增加,使用 SSL/TLS 證書來保護網站已成為一項必要措施。Let’s Encrypt 是一個免費的證書頒發機構,提供自動化的 SSL 證書申請和更新服務。本文將介紹如何在 Ubuntu 18.04 上使用 Let’s Encrypt 來保護 Nginx 伺服器。

前期準備

在開始之前,請確保您已經安裝了 Nginx 並且擁有一個有效的域名。您還需要在伺服器上安裝 Certbot,這是一個用於獲取和管理 Let’s Encrypt 證書的工具。

安裝 Nginx

sudo apt update
sudo apt install nginx

安裝 Certbot

接下來,您需要安裝 Certbot 及其 Nginx 插件。可以通過以下命令進行安裝:

sudo apt install certbot python3-certbot-nginx

獲取 SSL 證書

安裝完成後,您可以使用 Certbot 獲取 SSL 證書。請運行以下命令:

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

請將 “yourdomain.com” 替換為您的實際域名。Certbot 將自動配置 Nginx 並獲取證書。在過程中,您需要提供電子郵件地址以接收重要的通知,並同意服務條款。

自動更新證書

Let’s Encrypt 的證書有效期為 90 天,因此建議設置自動更新。Certbot 提供了一個簡單的方法來實現這一點。您可以通過以下命令來測試自動更新:

sudo certbot renew --dry-run

如果測試成功,您可以將自動更新任務添加到 crontab 中。運行以下命令來編輯 crontab:

sudo crontab -e

然後添加以下行以每天運行自動更新:

0 0 * * * /usr/bin/certbot renew >> /var/log/letsencrypt/letsencrypt.log

配置 Nginx

在獲取證書後,Certbot 會自動配置 Nginx。如果您需要手動配置,請編輯 Nginx 配置文件:

sudo nano /etc/nginx/sites-available/default

確保您的配置文件中包含以下內容:

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name yourdomain.com www.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;

    location / {
        proxy_pass http://localhost:3000; # 根據您的應用程序調整
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

完成後,檢查 Nginx 配置是否正確:

sudo nginx -t

如果沒有錯誤,重新啟動 Nginx 以應用更改:

sudo systemctl restart nginx

總結

使用 Let’s Encrypt 為 Nginx 配置 SSL 證書是一個簡單而有效的方式來提高網站的安全性。通過上述步驟,您可以在 Ubuntu 18.04 上輕鬆實現 HTTPS 保護。對於需要穩定和安全的網站,選擇合適的 VPS 解決方案是至關重要的。無論是個人網站還是商業應用,確保您的伺服器安全是每個網站管理員的責任。