Nginx作为大多数人选用的web服务器,尤其是用Node.js作为后台开发时,Nginx作为反向代理工具必不可少。certbot是一个免费SSL证书的CA,和nginx搭配两者可以轻松的搭建https网站。
准备条件
系统: CentOS 7 服务器: Nginx 登陆账户: ROOT
安装Certbot
在计算机上的命令行终端中运行以下命令以安装Certbot:
sudo yum install certbot python2-certbot-nginx
生成证书
运行以下命令以获取证书,并让Certbot自动编辑Nginx配置以为其提供服务,只需一步即可打开HTTPS访问。
certbot --nginx
如果你希望只希望生成证书然后手动配置nginx,需要运行以下命令:
certbot certonly --nginx
然后,certbot将会自动搜索可用的nginx配置,如下图所示:
[root@VM_16_12_centos ~]# certbot certonly --nginx
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org
Which names would you like to activate HTTPS for?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: cloud.gogoing.site
2: git.gogoing.site
3: www.gogoing.site
4: xsg.gogoing.site
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate numbers separated by commas and/or spaces, or leave input
blank to select all options shown (Enter 'c' to cancel):
在终端中输入域名对应的序号(1, 2, 3,4)继续生成证书,如果需要取消,则输入c
。 完成后,证书将保存在以下位置/etc/letsencrypt/live/域名/privkey.pem
配置nginx
打开nginx配置文件nginx.conf
,添加ssl_certificate
和ssl_certificate_key
配置:
server {
listen 80;
server_name www.gogoing.site;
# redirct to https
rewrite ^(.*)$ https://www.gogoing.site$1 permanent;
}
# Settings for a TLS enabled server.
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name www.gogoing.site;
root /usr/share/nginx/html;
ssl_certificate /etc/letsencrypt/live/www.gogoing.site/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/www.gogoing.site/privkey.pem; # managed by Certbot
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 10m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
}
配置完成后,运行命令systemctl reload nginx
重启nginx,再次打开网站,即可看到网站https已经配置成功!
自动续订证书
SSL证书的有效期为90天,并且Certbot已设置为自动续订。要模拟并测试驱动续订过程,请运行:
echo "0 0,12 * * * root python -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew -q" | sudo tee -a /etc/crontab > /dev/null
如果你不确定证书是否自动更新,可以尝试手动运行命令以检查证书是否到期:
certbot renew --dry-run
就是这样,现在您的WEB服务器就可以在HTTPS上成功运行,而无需您进行任何其他更改。
更多服务器配置请见: https://certbot.eff.org/