CA机构选择免费的Let's Encrypt。
Certbot
一个自动化申请 Let's Encrypt 证书的工具。
安装
yum install certbot
Standalone模式申请
先关闭占用80端口的nginx服务。
/etc/init.d/nginx stop
运行certbot。
certbot certonly
根据提示输入域名等信息,第一次运行会要求输入邮箱注册等信息。
完成后密钥会在/etc/letsencrypt/live/test.com(你的域名)/
下
恢复nginx服务。
/ect/init.d/nginx start
Webroot模式申请
--webroot
模式会在/www/your_website.com
中创建.well-known
文件夹,这个文件夹里面包含了一些验证文件,certbot 会通过访问your_website.com/.well-known/acme-challenge
来验证你的域名是否绑定的这个服务器。这个文件夹就是你Nginx
下index.html
所在的目录,请自行根据自己服务器 Nginx 的配置情况修改这个参数。——摘抄自网络,未尝试过。
certbot certonly --webroot -w /www/your_website.com -d test.com -d www.test.com
nginx配置HTTPS
主要是添加http强转https 以及添加https密钥路径。
server
{
# 强转https
listen 80;
server_name www.test.com test.com;
rewrite ^(.*)$ https://$host$uri;
}
server
{
listen 443 http2;
server_name www.test.com test.com;
# 开启ssl
ssl on;
ssl_certificate /etc/letsencrypt/live/test.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/test.com/privkey.pem;
# index.html入口文件目录
root /www/Test;
index index.html index.htm;
# 针对前端框架的history路由
location / {
try_files $uri $uri/ /index.html;
}
# 反向代理,并将内部后台接口升级成https
location ~ /api/ {
add_header Content-Security-Policy upgrade-insecure-requests;
proxy_pass http://localhost:5000;
}
# 资源文件设置强缓存 长期缓存
location ^~ /static/media/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}
}
设置自动续期
Let's Encrypt 的证书有效期为三个月,需要定时续期。
测试续期功能
跟申请证书流程差不多,先关闭占用80端口的nginx服务。
certbot renew --dry-run
没爆红报错基本就没问题可以添加定时任务了。
添加定时任务
crontab -e
追加写入每两个月四点半续期。
30 4 * */2 * root certbot renew --pre-hook "关闭nginx服务的命令" --post-hook "开启nginx服务的命令"
HTTPS优化
可能报的错
ImportError: cannot import name UnrewindableBodyError
Google搜了下,可能是yum与pip混用安装导致的。
解决方法很简单,统一以下就是了,卸载重装以下requests
和urllib3
这两个玩意。
sudo pip uninstall requests
sudo pip uninstall urllib3
sudo yum remove python-urllib3
sudo yum remove python-requests
sudo yum install python-urllib3
sudo yum install python-requests
Problem binding to port 80: Could not bind to IPv4 or IPv6..
80端口被占用了。
关闭相关服务再继续申请证书即可。