# Nginx 搭配Let’s Encrypt Certbot自動更新SSL憑證

#### **運行環境**

- **Ubuntu 22.04**

#### **下載certbot**

```
apt install certbot python3-certbot-nginx
```

```
certbot certonly --nginx -d your_frontend_fqdn
```

**輸入電子郵件用於通知**

#### **成功取得SSL憑證**

```
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Requesting a certificate for your_frontend_fqdn

Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/your_frontend_fqdn/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/your_frontend_fqdn/privkey.pem
```

#### **修改Nginx設定**

```
listen 443 ssl;
        ssl_certificate /etc/letsencrypt/live/your_frontend_fqdn/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/your_frontend_fqdn/privkey.pem;
```

```
nginx -t
systemctl restart nginx
```

**登入網站確認可使用https瀏覽**

#### **測試憑證**

```
#手動更新憑證
certbot renew   
#測試更新憑證
certbot renew --dry-run
#確認憑證狀態
certbot certificates
```

#### **使用CertBot 自動更新憑證**

**確認certbot.timer是否有啟動**

```
systemctl status certbot.timer
```

**編輯`/lib/systemd/system/certbot.service`，修改ExecStart**

```
[Unit]
Description=Certbot
Documentation=file:///usr/share/doc/python-certbot-doc/html/index.html
Documentation=https://certbot.eff.org/docs
[Service]
Type=oneshot
ExecStart=/usr/bin/certbot -q renew --post-hook "systemctl reload nginx"
PrivateTmp=true
```

```
systemctl start certbot.service
```

**如無錯誤訊息代表設定成功**

```
user@nginx-proxy:~#  service certbot status
* certbot.service - Certbot
     Loaded: loaded (/lib/systemd/system/certbot.service; static)
     Active: inactive (dead) since Thu 2025-07-17 15:30:48 CST; 11min ago
TriggeredBy: * certbot.timer
       Docs: file:///usr/share/doc/python-certbot-doc/html/index.html
             https://certbot.eff.org/docs
    Process: 3737646 ExecStart=/usr/bin/certbot -q renew --post-hook systemctl reload nginx (code=exited, status=0/SUCCESS)
   Main PID: 3737646 (code=exited, status=0/SUCCESS)
        CPU: 8.533s

Jul 17 15:28:06 nginx-proxy systemd[1]: Starting Certbot...
Jul 17 15:30:48 nginx-proxy systemd[1]: certbot.service: Deactivated successfully.
Jul 17 15:30:48 nginx-proxy systemd[1]: Finished Certbot.
Jul 17 15:30:48 nginx-proxy systemd[1]: certbot.service: Consumed 8.533s CPU time.
```