Nginx、CentOS环境使用Certbot申请免费SSL/HTTPS证书

122 阅读2分钟

CentOS安装snapd

  • 将 EPEL 添加到 CentOS 7
sudo yum install epel-release
  • 安装snapd
sudo yum install snapd
  • 启用snapd.socket:
sudo systemctl enable --now snapd.socket
  • 重启

安装Certbot

  • 安装 Certbot
sudo snap install --classic certbot
  • 如果之前有安装过记得删除
sudo yum remove certbot
  • 执行以下,确保certbot命令可以运行。
sudo ln -s /snap/bin/certbot /usr/bin/certbot

安装证书

  • 安装证书,并自动配置nginx.conf文件
sudo certbot --nginx
  • 如果配置文件存在于非标准位置/etc/nginx/nginx.conf,可以使用 --nginx-server-root 参数来指定 Nginx 配置文件的路径,注意指定到nginx.conf所在的文件夹即可,例如/opt/nginx/conf/nginx.conf
sudo certbot --nginx --nginx-server-root=/opt/nginx/conf
  • 如果不需要自动配置nginx.conf
sudo certbot certonly --nginx
  • 如果出现The error was:PluginError('Nginx build is missing SSL module (-- with-http_ssl_module).'),说明安装Nginx时没有ssl_module,可以使用预编译的版本或用yum重新安装,如果自己编译记得--with-http_ssl_module,举个栗子:
// 配置文件路径 安装路径 fastdfs模块 http_ssl_module
sudo ./configure --prefix=/opt/nginx --sbin-path=/usr/bin/nginx --add-module=/root/file/fastdfs-nginx-module/src --with-http_ssl_module

sudo make && sudo make install

// 验证 Nginx 是否包含 SSL 模块
nginx -V 2>&1 | grep -- '--with-http_ssl_module' 
  • 出现以下即安装成功
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Enter email address (used for urgent renewal and security notices)
这里输入邮箱会收到紧急续订和安全通知

Would you be willing, once your first certificate is successfully issued, to
这个yn都行

Which names would you like to activate HTTPS for?
为哪些激活,直接回车全选即可,后面哪个不需要自己改写nginx.conf即可
  • 测试自动续订
sudo certbot renew --dry-run

使用

  • 编辑nginx.conf文件,会发现server {}里多了几行监听443和密钥位置的配置,底部还有重定向的,不需要重定向可以删掉,例如接口,需要同时http和https复制一个server {}没有监听443的即可。
  • 记得重启nginx
sudo nginx -t # 验证nginx.conf
sudo systemctl reload nginx # 重新加载nginx配置
nginx # 启动
nginx -s stop # 停止
nginx -s reload # 重新加载配置