给 Astro 博客加上 HTTPS
接上一篇:站点已能用 http 打开,还差一张证书。证书加在 Nginx 层,Astro 静态站不用改代码。
一、拿到证书
Let’s Encrypt 签发时会访问 http://<域名>/.well-known/acme-challenge/<token> 确认域名归属,下面配置里的第一个 location 就是给它留的。
sudo apt-get install -y -qq certbot
sudo certbot certonly --webroot -w /var/www/letsencrypt \
-d fishcompanion.top -d www.fishcompanion.top \
--non-interactive --agree-tos --register-unsafely-without-email
签发后得到两个文件:/etc/letsencrypt/live/fishcompanion.top/fullchain.pem(证书链)和 privkey.pem(私钥)。私钥只留在服务器上,别提交进仓库。
二、绑定到 Nginx
「加 HTTPS」的实质就是这一步:在 443 的 server 块里用两条指令指向那两个文件,并让 80 的请求跳过去。
server {
listen 80;
server_name fishcompanion.top www.fishcompanion.top;
location ^~ /.well-known/acme-challenge/ {
root /var/www/letsencrypt;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
server_name fishcompanion.top www.fishcompanion.top;
ssl_certificate /etc/letsencrypt/live/fishcompanion.top/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/fishcompanion.top/privkey.pem;
root /var/www/fishcompanion;
index index.html;
location / {
try_files $uri $uri/ $uri/index.html =404;
}
}
ssl_certificate收证书链,ssl_certificate_key收私钥,必须配套;- 80 段别整段 301,保留验证目录供续期使用;
- 证书签发前不能先写 443 段:文件还不存在,
nginx -t会失败。顺序是先加验证目录 → 签发 → 换完整配置。
sudo nginx -t && sudo systemctl reload nginx
三、让绑定一直有效
证书 90 天到期,certbot 会自动续期,但续期只替换磁盘上的文件,Nginx 不重载就还在用内存里的旧证书:
sudo tee /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh <<'EOF'
#!/bin/sh
systemctl reload nginx
EOF
sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh
验证:certbot renew --dry-run、curl -I http://<域名> 返回 301、curl -I https://<域名> 返回 200。