Linux域名证书安装指南(以Let’s Encrypt+Certbot为例)
sudo apt update && sudo apt install certbot python3-certbot-nginxsudo yum install epel-release),再执行sudo yum install certbot python3-certbot-nginx。使用Certbot的Nginx插件自动完成证书申请与Web服务器配置:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
-d:指定主域名及子域名(如需泛域名支持,见下文“泛域名证书”);/etc/nginx/sites-available/yourdomain.conf),添加HTTPS监听端口(443)及证书路径。若需手动配置,需先获取证书文件(从CA处下载,通常包含.crt主证书、.key私钥、.ca-bundle中间证书链),并上传至服务器安全目录(如/etc/ssl/yourdomain/):
sudo mkdir -p /etc/ssl/yourdomain
sudo cp yourdomain.crt /etc/ssl/yourdomain/
sudo cp yourdomain.key /etc/ssl/yourdomain/
sudo cp ca_bundle.crt /etc/ssl/yourdomain/ # 可选,部分CA会提供
配置Nginx:编辑站点配置文件,添加以下内容:
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/ssl/yourdomain/yourdomain.crt; # 主证书路径
ssl_certificate_key /etc/ssl/yourdomain/yourdomain.key; # 私钥路径
ssl_trusted_certificate /etc/ssl/yourdomain/ca_bundle.crt; # 中间证书链(可选)
# SSL优化配置(可选)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256";
# 其他站点配置(如root目录、index文件)
root /var/www/html;
index index.html;
}
强制HTTP跳转HTTPS:添加以下server块,将80端口的HTTP请求重定向至443端口:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
return 301 https://$host$request_uri;
}
测试并重启Nginx:
sudo nginx -t # 检查配置语法
sudo systemctl restart nginx # 重启服务
若需支持*.yourdomain.com泛域名,需使用DNS验证方式(手动添加TXT记录):
sudo certbot certonly --manual --preferred-challenges dns -d *.yourdomain.com -d yourdomain.com
_acme-challenge.yourdomain.com的TXT记录(记录值为命令输出的字符串);/etc/letsencrypt/live/yourdomain.com/目录。Let’s Encrypt证书有效期为90天,需配置自动续期以避免过期:
sudo certbot renew --dry-run(模拟续期流程,无实际修改);sudo crontab -e),添加以下内容(每天凌晨3点检查续期,成功后重启Nginx):0 3 * * * /usr/bin/certbot renew --quiet --post-hook "systemctl reload nginx"
.key)需设置为仅root可读,避免泄露:sudo chmod 600 /etc/ssl/yourdomain/yourdomain.key
cat yourdomain.crt ca_bundle.crt > combined.crt),并更新Nginx配置中的ssl_certificate路径。sudo ufw allow 443/tcp # Ubuntu(ufw防火墙)
sudo firewall-cmd --add-port=443/tcp --permanent && sudo firewall-cmd --reload # CentOS(firewalld)