前往闪闪の小窝以获得更好的阅读和评论体验
一、背景介绍
Let’s Encrypt是一个免费、非营利性的开放证书权威中心,由互联网安全研究小组(ISRG)支持,签发的免费证书被各个主流浏览器认可。任何域名持有人均可使用Let’s Encrypt申请免费证书来加密网站流量,公司、机构则建议付费获取OV、EV证书。
给域名正确配置SSL证书可以解决NET::ERR_CERT_COMMON_NAME_INVALID报错
需要的东西:
- 一个域名(例如moechun.fun)
- 一台基于CentOS 7/8操作系统的vps。如果操作系统与本博客的有差异,请参考官方指引获取证书。
- 你的vps需要安装好Nginx
PS:域名没备案且vps在国内,可能无法申请成功
二、安装certbot
首先安装certbot
:
yum install -y python3 && pip3 install certbot
(注意:该安装方式不是官方推荐的,但一直都很好使)
安装完毕后,运行certbot --help
可以查看该工具的用法。
三、certbot 获取域名证书的步骤
1. 解析域名
进入域名的dns解析后台,将申请证书的域名记录指向服务器IP
2. 获取证书
certbot
默认使用http方式对域名所有权进行验证,该操作需要绑定vps的80端口。如果80端口已被占用,请先停止占用的进程,例如停止Nginx:systemctl stop nginx
。
阿里云、腾讯云等购买的服务器,还需要在vps网页后台的安全组中放行80端口。
接着运行命令为域名moechun.fun
和www.moechun.fun
获取证书:
certbot certonly --standalone -d moechun.fun -d www.moechun.fun
如果有其他二级域名,继续添加-d参数即可。
如果域名记录未指向服务器的IP,会报错并提示域名解析问题。
大概半分钟就拿到了免费的证书,运行 certbot certificates
命令可查看域名证书的路径和国旗时间。
3. 配置web服务器使用证书
我博客的配置文件在/usr/local/nginx/conf/conf.d/moechun.fun.conf
,编辑其内容为:
server {
listen 80;
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
# 监听的域名名称
server_name moechun.fun;
# 此处填写的是域名证书路径,cerbot会返回告诉你在哪
ssl_certificate /etc/nginx/ssl/fullchain.cer;
ssl_certificate_key /etc/nginx/ssl/moechun.fun.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
# 为了增强安全性,ssl_protocols、ssl_ciphers和ssl_prefer_server_ciphers的配置建议采用以下配置。
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
ssl_ecdh_curve secp384r1;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
keepalive_timeout 70;
location / {
# 我就是在这设置Nginx监听域名,如果是moechun.fun就转去4000端口,也就是我Hexo的端口号
proxy_pass http://localhost:4000;
root /www;
}
error_page 401 403 404 /404.html;
location = /404.html {
root html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
ssl_prefer_server_ciphers on;
配置好以后,运行nginx -t
命令查看有无错误。配置正确的话用systemctl restart nginx
重新启动nginx。
https使用443端口,如果开启了防火墙,记得放行https服务:
firewall-cmd --permanent --add-service=https
# 如果监听了其他端口,使用下面的命令
# firewall-cmd --permanent --add-port=端口号/tcp
firewall-cmd --reload
四、证书自动更新
Let’s Encrypt证书的有效期是三个月,超过期限则需要续签。证书续期可以手动完成,例如:
systemctl stop nginx
certbot renew
systemctl restart nginx
也可以配置crontab任务自动续签,在/etc/crontab文件末添加一行:
0 0 1 */2 0 root systemctl stop nginx; /usr/local/bin/certbot renew; systemctl restart nginx
pip3默认安装的certbot路径是/usr/local/bin/certbot
,可使用 which certbot
查看,如果输出不同,请记得替换。该配置将每两个月自动运行certbot并续签证书。如果你的证书快到期了还没有续签,贴心的EFF(电子前哨基金会)会发邮件提醒,记得到期前续签就行。