«

Nginx配置HTTPS,Let's Encrypt免费SSL证书申请

时间:2026-10-5 07:54     作者:emer     分类: 无


前言

现在网站没个 HTTPS 都不好意思拿出来,浏览器直接标"不安全"。申请 SSL 证书以前要花钱买,现在有了 Let's Encrypt,免费申请,90天有效期,还能自动续期。本文就讲一下怎么用 Let's Encrypt 给 Nginx 配 HTTPS。

前提条件

申请 SSL 证书之前,先确认:

  1. 域名已经解析到服务器 IP
  2. 80 端口已经开放(防火墙、安全组都要开)
  3. Nginx 已经能正常跑 HTTP

这三个条件满足了才能申请成功。

第一步:安装 certbot

certbot 是 Let's Encrypt 官方的证书申请工具。

yum install certbot python2-certbot-nginx -y

这个包会自动装 certbot 和 Nginx 插件。

第二步:申请证书

自动申请并配置

certbot --nginx -d www.example.com -d example.com

参数说明:

执行过程中会问你:

  1. 邮箱地址:填你的邮箱,证书过期了会提醒你
  2. 同意服务条款:输入 A
  3. 是否接收邮件:输入 N
  4. 是否把 HTTP 跳转到 HTTPS:选 2(跳转)

等待申请完成,一般几秒钟就好。

第三步:测试 HTTPS

浏览器访问 https://www.example.com,应该能看到小锁标志了。

HTTP 访问 http://www.example.com 会自动跳转到 HTTPS。

证书文件位置

申请完的证书文件都在 /etc/letsencrypt/live/域名/ 目录下:

/etc/letsencrypt/live/www.example.com/
├── cert.pem          # 证书
├── chain.pem         # 中间证书
├── fullchain.pem     # 证书+中间证书(Nginx用这个)
└── privkey.pem       # 私钥

Nginx 配置里用的是:

自动续期

Let's Encrypt 证书有效期只有 90 天,需要定期续期。

测试自动续期

certbot renew --dry-run

如果没报错,说明自动续期配置没问题。

自动续期定时任务

certbot 装完会自动加一个定时任务,不用管。可以看看:

crontab -l

或者:

systemctl list-timers | grep certbot

手动配置 HTTPS

如果不想用 certbot 自动改配置,也可以手动写 Nginx 配置。

Nginx HTTPS 配置示例

server {
    listen 80;
    server_name www.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name www.example.com;

    ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    root   /var/www/html/test;
    index  index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }
}

检查并重载

nginx -t
systemctl reload nginx

常见坑

坑1:域名没解析就申请

域名还没解析到服务器,就开始申请证书,结果申请失败。

解决: 先 ping 一下域名,确认解析到你服务器 IP 了再申请。

坑2:80 端口没开

防火墙或安全组没开 80 端口,Let's Encrypt 验证不了你的域名,申请失败。

解决: 先开 80 端口:

firewall-cmd --permanent --add-service=http
firewall-cmd --reload

云服务器还要在安全组里开 80 端口。

坑3:证书到期了没续期

忘了续期,证书过期了,浏览器报不安全。

解决: certbot 会自动续期,不用管。但要确认自动续期服务在运行:

systemctl status certbot-renew.timer

坑4:HTTPS 配置完了 404

配完 HTTPS 访问 404,一般是 root 目录或者 server_name 写错了。

排查:

  1. 看 Nginx 配置里的 server_name 对不对
  2. 看 root 目录对不对
  3. nginx -t 检查配置语法

总结

Nginx 配置 HTTPS 的完整流程:

  1. 装 certbot:yum install certbot python2-certbot-nginx -y
  2. 申请证书:certbot --nginx -d www.example.com
  3. 自动续期:certbot 自动搞定,不用管
  4. 测试:浏览器访问 HTTPS,看小锁标志

Let's Encrypt 免费证书是现在最流行的方案,不用花钱就能给网站上 HTTPS。

遇到问题加QQ23979811 协助处理

标签: Nginx HTTPS SSL证书 Let\'s Encrypt certbot