天天看點

Nginx配置ssl實作https全站通路

以 Let.s Encrypt為例,個人覺得其比較簡單,而且免費版各大浏覽器也支援。

1,mkdir -p /網站根目錄/.well-known/acme-challenge 建立臨時目錄,當然這個網站根目錄根據你自己的實際情況修改。如果以前生成過不用重複生成。

2,cd 到任何自己喜歡的目錄,比如root 家目錄 cd /root 然後執行

$ wget https://dl.eff.org/certbot-auto
$ chmod a+x ./certbot-auto
           

這個小工具會在安裝證書的時候自動下載下傳并安裝相關依賴和 Python 包,也可以先執行它來安裝依賴

$ ./certbot-auto
           

稍等一下就完成了。

3,生成證書過程中需要鑒權。有多種方式,比如

webroot

standalone

apache

nginx

manual

等。我使用過前兩種。 這兩種中,簡單一點的是

standalone

。不過,這種方式需要把現有的 WebServer 停掉,因為這種方式下 certbot 需要占用 80 端口。

以下幾種方式的配置中 -d 代表 domain 填寫域名   -w 代表 wwwroot 填寫網站根目錄

第一種 :         standalone                  # ./certbot-auto certonly --text --agree-tos --email [email protected] --standalone -d example.com -d www.example.com -d service.example.com      

第二種,推薦第二種

webroot

-d

參數指定域名,可多個。一般第一個是主域名。

webroot

方式稍微繁瑣一些,但好處是不需要關停現有的 WebServer 。此方法需要在域名對應的根目錄下建立

.well-known

目錄并寫入若幹檔案供驗證服務通路。 是以需要配置 WebServer 允許外部通路

http://example.com/.well-known

路徑。配置方法請參考相應 WebServer 的文檔,我的配置是:在server中加入:

  location ~ /.well-known {

            root 網站目錄;

           allow all;

        }

然後執行證書安裝:

# ./certbot-auto certonly --text --agree-tos --email [email protected] --webroot -w /var/www/example -d example.com -d www.example.com -w /var/service/example -d service.ulefa.com
           

無論使用那種方式,運作以上指令後都會在

/etc/letsencrypt

生成一堆東西,包括證書。

4,安裝完成後能看到 Congratulations! Your certificate and chain have been saved at:等等一堆資訊裡面提供了配置ssl需要的證書路徑。

現在修改nginx的配置檔案即可:

  1. 打開 Nginx 的配置檔案(預設為:

    /etc/nginx/nginx.conf

    ),在需要提供 HTTPS 的

    server

    下新增以下三行,并把

    listen 80;

    删掉,不删掉的話非ssl仍能通路,建議删掉後另起一個server做301配置。
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
           
另起一個server做301如下:
server {
listen   80;
server_name example.com www.example.com service.example.com;
return 301 https://$host$request_uri;
}
           

5,

定期 renew

Let's Encrypt 的證書有效期為 90 天,是以需要在到期前 renew 一下證書。 使用以下指令即可。

# ./certbot-auto renew --text --agree-tos --email [email protected] --webroot -w /var/www/example -d example.com -d www.example.com -w /var/service/example -d service.ulefa.com
           

即把certonly 改為renew即可。

或者直接運作以下指令,此時 certbot 會使用預設參數,在二級域名分别使用各自的證書情況下慎用,有調用次數限制。

# ./certbot-auto renew
           

crontab

裡加入定時任務,每隔 80 天的淩晨 4 點執行一次 renew:

0 4 */80 * * /yourpath/certbot-auto renew &>> /dev/null
           

當然,最後記得如果網站背景有配置域名的話,需要将其改為https://www.yourdomain.com

繼續閱讀