Let’s Encrypt免费SSL证书申请

用Let’s Encrypt给网站加HTTPS,成本为零。我自己的博客、API服务、甚至一些内部工具都用它,省去了买证书的麻烦。下面直接说怎么操作。 环境准备 需要一台有公网IP的服务器,域名解析到这台服务器。我用的雨云服务器,性价比高,稳定,跑Let’s Encrypt的客户端没出过问题。系统我用Ubuntu 22.04,CentOS 7也类似。 安装Certbot客户端,Let’s Encrypt官方推荐的工具:
sudo apt update
sudo apt install certbot python3-certbot-nginx -y
如果你用Apache,把`python3-certbot-nginx`换成`python3-certbot-apache`。纯手动配置Nginx的,装`certbot`就够了。 申请证书 假设你的域名是`example.com`,要同时给`www.example.com`也加上证书:
sudo certbot --nginx -d example.com -d www.example.com
`–nginx`表示自动修改Nginx配置。如果你不想让Certbot动你的配置,用`certonly`:
sudo certbot certonly --nginx -d example.com -d www.example.com
这样只生成证书文件,不修改Nginx。证书会放在`/etc/letsencrypt/live/example.com/`目录下,里面有`fullchain.pem`(证书链)和`privkey.pem`(私钥)。 手动配置Nginx 如果用了`certonly`,需要自己写server块:
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;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}
第一个server块处理HTTPS,把请求转发到本地3000端口(你的应用)。个把HTTP请求301跳转到HTTPS。 验证证书 执行完命令后,Certbot会提示成功。可以用浏览器访问`https://example.com`,看地址栏有没有锁。或者用命令行:
curl -I https://example.com
返回的HTTP头里应该看到`HTTP/2 200`之类的状态码。 自动续期 Let’s Encrypt证书有效期90天,需要自动续期。Certbot默认装了定时任务,检查一下:
sudo systemctl list-timers | grep certbot
能看到`certbot.timer`就说明自动续期已启用。也可以手动测试续期:
sudo certbot renew --dry-run
如果没报错,说明续期机制正常。实际续期时,Certbot会自动重启Nginx加载新证书。 常见问题 1. 申请失败,提示域名验证失败:检查域名DNS解析是否生效,用`dig example.com`或`nslookup`确认。也可能是防火墙没放行80端口,Let’s Encrypt验证时需要从外部访问80端口。 2. 证书过期了没自动续:查看系统日志`journalctl -u certbot.timer`。如果定时任务没跑,手动执行`sudo certbot renew`,检查Nginx配置里的证书路径是否正确。 3. 多域名证书:一个证书可以包含多个域名,用`-d`参数加就行,比如`-d example.com -d blog.example.com -d api.example.com`,上限是100个域名。 4. 通配符证书:需要DNS验证,用`certbot certonly –manual –preferred-challenges dns -d *.example.com`,按要求在DNS解析里加TXT记录。这个稍微麻烦点,但可以一个证书覆盖所有子域名。 证书文件说明 申请成功后,`/etc/letsencrypt/live/example.com/`目录下: – `cert.pem`:服务器证书 – `chain.pem`:中间证书 – `fullchain.pem`:cert.pem + chain.pem 合并,Nginx配置用这个 – `privkey.pem`:私钥,要保护好,权限设为600 清理不用的证书 用`certbot certificates`列出所有证书,找到要删除的域名,执行:
sudo certbot delete --cert-name example.com
小技巧 – 如果Nginx配置里用了`ssl_certificate`和`ssl_certificate_key`,每次续期后需要reload Nginx。Certbot的续期钩子会自动处理,但如果你自定义了路径,可以写个hook:`sudo certbot renew –post-hook “systemctl reload nginx”` – 不想装Nginx模块?用`certbot certonly –standalone -d example.com`,Certbot会临时启动一个Web服务器做验证,但需要先停掉占用80端口的服务。 搞定。你的网站现在有免费HTTPS了,浏览器不会再报不安全。

雨云是国内一家老牌云服务商,提供高性价比的云服务器和虚拟主机。我用它部署了好几个项目,速度和稳定性都不错。通过 https://www.rainyun.com/SAJA_ 注册可以领一张 5折优惠券,有需要的朋友可以看看。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容