現在身為一個21世紀的 web 沒有上個 ssl 怎麼算是很潮的 web ,剛好趕搭最近 letencrypt 正式開始,就來幫我幾個 Domain 做 ssl 加密

目前它官方提供出來的 plugin 只有 apache,nginx 版的問題好像還不少,所以還是要手動設定,首先照著它的說明

$ git clone https://github.com/letsencrypt/letsencrypt
$ cd letsencrypt

他有提供兩種憑證驗證方式

  • webroot
  • standalone

兩者差異在於,webroot,驗證時不用關閉現有web 服務,ex nginx,apache…,他的原理是在你的 web root 寫一個檔案,然後由他的server來存取值這個檔案,驗證這個 domain 屬於你這台主機,後者則是會自己啟動一個 web 服務,所以才需要關掉現有服務。

我個人比較推薦用 webroot來做驗證,因為這個 letsencrypt 所發的憑證要3個月 renwe 一次,這樣未來在 renew 時,不會因此造成你的 web 服務暫時性的中斷。

接下來我們來看看 如何用 webroot 設定

$ ./letsencrypt-auto certonly --webroot -w /var/www/example -d example.com -d www.example.com -w /var/www/thing -d thing.is -d m.thing.is

它可以指定不同的 web root 一個root 可以掛上不同的 domain,在 -w 之後可以掛上 -d,基本上一個 -w就會有1個 或 N個 -d

在來看看 nginx 的設定

首先先把 原本這行的設定註解掉

listen 80;

加入以下這些

listen 443 ssl;

# 執行完上面的憑證驗證,它自動會在/etc/letsencrypt/live 下面產生 domain 的資料夾
ssl_certificate /etc/letsencrypt/live/YourDomain/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/YourDomain/privkey.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDH+AESGCM:EDCH+AES256:ECDH+AES128:!MD5:!aNULL;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1h;
ssl_stapling on;
ssl_stapling_verify on;

如果要強制把http 轉導到 https 則加入以下設定

server {
    listen 80;
    server_name YourDomain;
    return 301 https://$host$request_uri;
}

當然上面有講過這個憑證有效期限只有3個月,所以我們需要固定時間來做 renew 的動作,這時侯就要靠 crontab 來幫忙了

首先我們自己先自己寫一段 script 取名叫做 le-renew.sh

#!/bin/sh
sudo /{path}/letsencrypt-auto certonly --webroot --renew-by-default --agree-tos -m [email protected] -w /webroot -d domain -w /webroot2 -d domain2 

記得要給他的執行權限

$ chmod +x le-renew.sh

然後下

$ sudo crontab -e

寫入

30 2 * * 1 /{path}/le-renew.sh >> /{path}/le-renew.log