不加密的HTTP通信,会有被挟持,数据篡改,数据窃听的风险,所以搭建完个人博客后考虑使用https协议。对于个人博客小站,https证书太贵,个人博客推荐使用 Let’s Encrypt,本文介绍使用 Certbot 生成证书,并配置nginx支持https。

certbot生成证书

1
2
3
4
git clone https://github.com/certbot/certbot
cd certbot
# 将 EMAIL DOMAINS 修改为你的email和域名
./certbot-auto certonly --standalone --email lzhujian@gmail.com -d kxcblog.com -d www.kxcblog.com

证书生成成功后,tree查看/etc/letsencrypt/live目录如下

1
2
3
4
5
6
7
8
9
# tree /etc/letsencrypt/live
/etc/letsencrypt/live/
├── kxcblog.com
│   ├── cert.pem -> ../../archive/kxcblog.com/cert2.pem
│   ├── chain.pem -> ../../archive/kxcblog.com/chain2.pem
│   ├── fullchain.pem -> ../../archive/kxcblog.com/fullchain2.pem
│   ├── privkey.pem -> ../../archive/kxcblog.com/privkey2.pem
│   └── README
└── README

nginx配置

nginx配置主要修改2点,1.添加SSL配置,2.将http请求改写为https

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
server {
    # SSL configuration
    #
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    ssl_certificate /etc/letsencrypt/live/kxcblog.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/kxcblog.com/privkey.pem;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
}
# redirect http => https
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    server_name kxcblog.com;
    rewrite ^(.*)$ https://kxcblog.com$1 permanent;
}

至此访问博客就能看的小锁了 :)

证书自动续期

certbot生成的证书有效期为90天,所以需要定期更新证书,本文通过crontab指定一个定期计划,每2个月的15号凌晨2点更新证书

1
2
3
4
5
# sudo crontab -u root -e
# 将如下定时任务加入到crontab
# m h  dom mon dow   command
# renew cert every 2 months on the 15th at 2am
0 2 15 */2 * /path_to_certbot/certbot/certbot-auto renew --standalone --pre-hook "systemctl stop nginx" --post-hook "systemctl start nginx" --force-renewal

以上,欢迎学习交流,lzhujian#gmail.com :)