在Ubuntu上使用Nginx配置自動續期SSL證書,通常會結合Certbot工具來實現。Certbot是一個由Let’s Encrypt提供的自動化工具,可以方便地獲取和續期SSL證書。以下是詳細步驟:
首先,確保你的系統是最新的,然后安裝Certbot及其Nginx插件。
sudo apt update
sudo apt install certbot python3-certbot-nginx
使用Certbot獲取SSL證書。假設你的域名是example.com
。
sudo certbot --nginx -d example.com -d www.example.com
在安裝過程中,Certbot會自動配置Nginx,并要求你輸入郵箱地址和同意Let’s Encrypt的服務條款。Certbot還會創建一個Nginx配置文件片段,通常位于/etc/letsencrypt/options-ssl-nginx.conf
。
確保Nginx配置文件中包含了Certbot生成的配置片段。編輯你的Nginx站點配置文件(例如/etc/nginx/sites-available/example.com
),確保包含以下內容:
server {
listen 80;
server_name example.com www.example.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
# 其他配置...
}
在重新加載Nginx之前,測試配置文件是否有語法錯誤。
sudo nginx -t
如果沒有錯誤,重新加載Nginx以應用更改。
sudo systemctl reload nginx
Certbot會自動設置一個cron任務來定期檢查并續期證書。你可以手動測試續期過程:
sudo certbot renew --dry-run
如果沒有問題,Certbot會自動續期證書,并更新Nginx配置文件中的證書路徑。
你可以使用以下命令查看Certbot的續期狀態:
sudo certbot renew --post-hook "systemctl reload nginx"
這個命令會在續期成功后重新加載Nginx。
通過以上步驟,你可以在Ubuntu上使用Nginx和Certbot配置自動續期SSL證書。Certbot會自動處理證書的獲取和續期,大大簡化了管理SSL證書的過程。