1. 程式人生 > >LINUX伺服器最簡潔的HTTPS免費證書配置方法

LINUX伺服器最簡潔的HTTPS免費證書配置方法

注意:該方法已在多臺伺服器配置了免費的https證書,無論是更新還是第一次配置都執行成功;由於是免費版,每個證書都只有三個月的有效期,也無法保證安全和穩定性,所以只建議做測試用,客戶的專案需要時,請讓購買正式版證書
一、配置https免費證書,確保伺服器已開啟443埠

    ①在root目錄下,執行下面命令:只有第一次安裝時需要執行,後面追加域名時不再需要
        wget https://dl.eff.org/certbot-auto
    
    ②停止nginx,必須停止,否則安裝證書時會報80埠被佔用
        service nginx stop
    
    ③追加多個域名
        // 
[email protected]
換成自己的常用郵箱,據說到期前會給發提醒郵件 // www.xieyouhui.com 換成自己需要配置https的域名,多個域名使用 -d 追加 ./certbot-auto certonly --standalone --email [email protected] --agree-tos -d www.xieyouhui.com -d app.xieyouhui.com -d admin.xieyouhui.com // 也能用於後期域名的追加 ./certbot-auto certonly --standalone --email
[email protected]
--agree-tos -d www.weimi888.com -d weimi888.com 如果出現./certbot-auto: Permission denied 錯誤,需要certbot-auto檔案擁有可執行許可權 ④檢視生成的證書 ls /etc/letsencrypt/live/ ⑤在nginx配置證書 //證書檔案需要開啟讀寫許可權 ssl_certificate /etc/letsencrypt/live/cdw.me/fullchain.pem;#證書位置 ssl_certificate_key /etc/letsencrypt/live/cdw.me/privkey.pem;# 私鑰位置 ⑥啟動nginx service nginx start 手動更新https證書 2、手動更新的方法,如果遇到更新報錯,可以重新執行上面第③條,重新申請證書 service nginx stop 停止nginx ./certbot-auto renew -v 執行更新方法,certbot-auto該檔案需要獲得執行許可權 service nginx start 啟動nginx 3、自動更新的方法 certbot-auto指令碼帶有自動更新證書功能,執行如下程式碼即可: // 該方法執行後,由於證書到期時間過長,還未證實是否有用 ./certbot-auto renew --quiet --no-self-upgrade 定時任務:不確定下面這倆定時任務是否都能使用,請自己測試 # 每月1號5時執行執行一次更新,並重啟nginx伺服器 00 05 01 * * /root/certbot renew --quiet && /bin/systemctl restart nginx #更新SSL證書 30 2 3 * * /root/letsencrypt/./letsencrypt-auto renew > /var/log/le-renew.log && nginx -s reload 二、配置域名,通用配置檔案下載地址,請按照提示更換成自己的資訊 https://liuniu.oss-cn-zhangjiakou.aliyuncs.com/xyh/peizhiwenjian.zip 三、查詢證書到期時間封裝方法 /** * 獲取SSL證書到期時間 * param $domain 需要查詢的域名,例如www.baidu.com * return array */ public function getValidity($domain){ $context = stream_context_create(array("ssl" => array("capture_peer_cert_chain" => true))); $socket = stream_socket_client("ssl://$domain:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context); $context = stream_context_get_params($socket); foreach ($context["options"]["ssl"]["peer_certificate_chain"] as $value) { //使用openssl擴充套件解析證書,這裡使用x509證書驗證函式 $cerInfo = openssl_x509_parse($value); if(strpos($cerInfo['name'],$domain)) { // 提前三天預警 $early_warning_time = time() - 3 * 24 * 3600; if ($cerInfo['validTo_time_t'] <= $early_warning_time) { $end_type = 1; } else { $end_type = 0; } $result = array( 'start_time' => date("Y-m-d H:i",$cerInfo['validFrom_time_t']), // 開始時間 'end_time' => date("Y-m-d H:i",$cerInfo['validTo_time_t']), // 到期時間 'end_type' => $end_type ); return $result; } } }