Nic Lin's Blog

喜歡在地上打滾的 Rails Developer

讓網站免費擁有 HTTPS 憑證,申請 Let’s Encrypt 並自動更新

現在連 Google chrome 都會把 http 標記為不安全了,想當然爾,HTTPS 加密連線的重要性不言可喻了

這邊就筆記一下如何在自己的機器上,自動 renew Let’s Encrypt 的免費憑證吧

安裝方式

在你的 VPS 機器上

$ mkdir -p /etc/dehydrated/
$ wget https://raw.githubusercontent.com/lukas2511/dehydrated/master/dehydrated -O /etc/dehydrated/dehydrated
$ chmod 755 /etc/dehydrated/dehydrated

建立設定檔

$ echo "WELLKNOWN=/var/www/dehydrated" > /etc/dehydrated/config 
$ mkdir -p /var/www/dehydrated

Nginx 設定,先在 80 port 的 server section 寫入底下設定,因為要從 http 進行驗證

location /.well-known/acme-challenge/ {
  alias /var/www/dehydrated/;
}

第一次使用要先同意聲明,先輸入

/etc/dehydrated/dehydrated --register --accept-terms

接著透過 dehydrated 指令產生 SSL 設定檔案

/etc/dehydrated/dehydrated -c -d niclin.tw

應該會看到 log

# INFO: Using main config file /etc/dehydrated/config
Processing niclin.tw
 + Signing domains...
 + Generating private key...
 + Generating signing request...
 + Requesting challenge for niclin.tw...
 + Responding to challenge for niclin.tw...
 + Challenge is valid!
 + Requesting certificate...
 + Checking certificate...
 + Done!
 + Creating fullchain.pem...
 + Done!

再將 nginx 做最後設定

server {
  # don't forget to tell on which port this server listens
  listen 80;
 
  # listen on the www host
  server_name niclin.tw;
 
  # and redirect to the non-www host (declared below)
  return 301 https://niclin.tw$request_uri;
}
 
server {
  listen 443 ssl http2;
  server_name niclin.tw;
 
  location /.well-known/acme-challenge/ {
    alias /var/www/dehydrated/;
  }
 
  ssl_certificate /etc/dehydrated/certs/niclin.tw//fullchain.pem;
  ssl_certificate_key /etc/dehydrated/certs/niclin.tw/privkey.pem;
}

上面是將 80 port 自動轉到 https,如果下次要重新 renew 的時候才不會又要打開 80 port 一次。

自動更新

將指令放在 /etc/cron.weekly 內執行

#!/bin/bash
export PATH=/usr/sbin:/usr/bin:/bin:"${PATH}"
sleep $(expr $(printf "\%d" "0x$(hostname | md5sum | cut -c 1-8)") \% 86400); ( /etc/dehydrated/dehydrated -c -d niclin.tw; service nginx reload ) > /tmp/dehydrated-niclin.tw.log 2>&1

參考來源

Share Comments
comments powered by Disqus