码上游记

hongjian.xia的个人博客

0%

Let's Encrypt HTTPS证书申请、安装及自动续期

概述

由于新版本的Chrome对于非HTTPS网站都会提示不安全,十分影响使用体验,所以打算把博客站点升级到HTTPS。

运行环境

此博客系统的运行环境是阿里云Ubuntu14.04(不记得当初买ECS的时候为什么会选这个版本,可能是忘记选了吧😂),Nginx, Spring Boot。

Nginx https模块支持

当初安装Nginx时没有配置支持https,所以需要重新编译一个支持httpps的Nginx。

首先确定自己的Nginx的版本及编译参数(如果支持https即可跳过接下来的步骤)。执行nginx -V,确定Nginx版本。

下载对应版本的Nginx源码,解压后进入目录, 执行以下命令

1
2
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-file-aio --with-http_realip_module
make

注意 --prefix需要输入自己的Nginx安装目录,否则运行Nginx时会出现无法打开log文件、配置文件等问题。
编译完毕后objs目录下就有个nginx文件,此文件就是我们需要的。

备份原来的Nginx程序。

1
cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak

kill Nginx进程,然后复制新编译的Nginx。

1
cp ./objs/nginx /usr/local/nginx/sbin/nginx

启动Nginx,完工。

安装Certbot-auto及证书生成

下载Certbot-auto, chmod +x certbot-auto添加运行执行权限。

这里我需要申请的是通配符证书,所以申请过程中需要为DNS增加一条TXT记录,为了方便以后自动续期(renew),需要用到另外一个项目certbot-letencrypt-wildcardcertificates-alydns-au,这个项目功能自动调用API为DNS添加TXT记录。

下载certbot-letencrypt-wildcardcertificates-alydns-au后需要在脚本中配置上自己的API Key。执行下面的命令测试(具体脚本的参数,参考项目的README)

1
./certbot-auto certonly  -d *.example.com --manual --preferred-challenges dns --dry-run  --manual-auth-hook "/脚本目录/au.sh php aly add" --manual-cleanup-hook "/脚本目录/au.sh php aly clean" 

没有问题后执行以下命令,正式生成证书

1
./certbot-auto certonly  -d *.example.com --manual --preferred-challenges dns --dry-run  --manual-auth-hook "/脚本目录/au.sh php aly add" --manual-cleanup-hook "/脚本目录/au.sh php aly clean" 

查看生成的证书

1
./certbot-auto certificates

证书续期

1
./certbot-auto renew  --manual --preferred-challenges dns --manual-auth-hook "/脚本目录/au.sh php aly add" --manual-cleanup-hook "/脚本目录/au.sh php aly clean"  

加入crontab
编辑文件 /etc/crontab :

1
2
#证书有效期<30天才会renew,所以crontab可以配置为1天或1周,成功续期后Nginx reload
1 1 */1 * * root certbot-auto renew --manual --preferred-challenges dns --deploy-hook "nginx -s reload"--manual-auth-hook "/脚本目录/au.sh php aly add" --manual-cleanup-hook "/脚本目录/au.sh php aly clean"

配置Nginx

编辑配置文件/usr/local/nginx/conf/nginx.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
## 将http请求转发到https
server {
listen 80;
server_name www.example.com example.com test.example.com;
rewrite ^(.*)$ https://$host$1 permanent;
}

server {
server_name www.example.com example.com test.example.com;
listen 443;
ssl on;
ssl_certificate /etc/letsencrypt/live/example.comfullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;

location / {
proxy_pass http://127.0.0.1:8080;

## 做反向代理需要设置请求header,防止丢失访问者的原IP
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

## websocket配置
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}

reload

1
nginx -s reload

🎉大功告成