0%

Ubuntu 使用Certbot 替Nginx自動掛上SSL憑證

前言

剛好有機會拿到一台新的API Server並將API部署到 Nginx上
因此趁著這次操作,順便紀錄一下,如何將Nginx掛上SSL憑證,並透過Certbot每個月自動 renew新的憑證

安裝Certbot

首先,我們需要先安裝Cerbot,待會將會透過它幫我們製作SSL憑證。

1
2
sudo apt-get update
sudo apt-get install certbot

建立憑證

接著,透過cerbot幫我們製作一個SSL憑證,這邊記得換上你購買的網域。

1
certbot certonly --standalone -d <你的domain name>
注意:在第一次建立憑證的時候,cerbot會先佔用你的80 port,因此如果有開啟Nginx記得要先關閉。 等建立完成後,再進行重啟。

在安裝完成後,預設會產生兩個檔案:ssl_certificatessl_certificate_key
這兩個預設的路徑會被放到:
ssl_certificate /etc/letsencrypt/live/<你的domain name>/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/<你的domain name>/privkey.pem;

在Nginx配置文件中加上SSL:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server {
listen 443 ssl;
server_name <你的domain name>;

ssl_certificate /etc/letsencrypt/live/<你的domain name>/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/<你的domain name>/privkey.pem;

location /api {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

重啟Nginx

完成後,記得重啟一下Ngnix確認套用certbot產生的SSL

1
2
nginx -t 
nginx -s reload

設定Crontab每個月重新renew一張新的憑證

由於Let’s Encrypt 的憑證每三個月就會到期,因此我們需要透過 certbot幫助我們自動renew新的憑證。
因此在最後完成後,我們需要設定Crontab,透過linux內建的排程功能,每個月就自動renew一次。

首先先開啟 crontab的文件,進行編輯:

1
crontab -e

接著我們在最後一行加上以下命令: (這邊我設定每個月的第一天就自動啟動 certbot進行renew)

1
0 0 1 * * certbot renew

完成後,輸入 Ctrl+O 存檔後Ctrl+X離開即可。

註:如果要確認是否有成功寫入,可以輸入 crontab -l 進行確認。
以上文章敘述如有錯誤及觀念不正確,請不吝嗇指教:)

有任何家教、案子 或技術相關問題 請都歡迎聯繫我

http://www.zhenghui.idv.tw/