Let’s Encrypt! 为博客开启https

看过之光的文章后,跃跃欲试,实践后整理了nginx的部分。
运行环境如下:

  • cat /etc/redhat-release > CentOS Linux release 7.2.1511 (Core)
  • nginx -v > nginx version: openresty/1.9.15.1
  • blog > hexo

用git下载客户端并安装依赖:

1
2
3
git clone https://github.com/letsencrypt/letsencrypt
cd letsencrypt
./letsencrypt-auto --help

开始申请

申请证书时客户端需要使用80和443端口,因此先停掉nginx:

1
sudo systemctl stop nginx

申请证书:

1
./letsencrypt-auto certonly --standalone

按照屏幕提示依次输入联系email、同意Terms of Service、输入域名。

配置Nginx

编辑nginx.conf /usr/local/nginx/conf/vhost/blog.walkcd.com.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
server
{
listen 80;
listen 443 ssl;

server_name blog.walkcd.com; #替换成自己的域名
index index.html;
root /home/www/blog.walkcd.com;
ssl_certificate /etc/letsencrypt/live/blog.walkcd.com/fullchain.pem; # 替换成自己的证书和密钥
ssl_certificate_key /etc/letsencrypt/live/blog.walkcd.com/privkey.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_dhparam /home/www/dhparam.pem;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

# 重定向到https
if ($server_port = 80){
return 301 https://$server_name$request_uri;
}

if ($scheme = http){
return 301 https://$server_name$request_uri;
}

error_page 497 https://$server_name$request_uri;

error_page 404 /404.html;
}

重新启动nginx

1
sudo systemctl start nginx

自动续期证书

由于Let’s Encrypt的证书有效期只有90天,因此编写一个脚本自动地renew证书:letsencrypt_renew.sh

1
2
3
4
#!/bin/bash
sudo systemctl stop nginx
/home/www/letsencrypt/letsencrypt-auto renew --force-renew
sudo systemctl start nginx

编辑crontab,每月1日自动调用脚本:

1
0 0 1 * * /home/www/letsencrypt/renew.sh >> /home/www/logs/letsencrypt_renew.log 2>&1

这样就大功告成了。