访问我网站的同学应该可以注意到,在左上角的位置我的域名前应该有个安全标志,不同版本和不同类型的浏览器展示的效果可能是不一样的,例如我使用 Version 72 的 Chrome 可能展示效果是这样的:

而使用 Version 60 的 Firefox 的展示效果又是这样的:

这些都和浏览器的策略有关,但是,可以明显发现的就是我的域名前缀是 https 的,不信你看看。https 可以保证你在查看我网站的时候看到的内容是我真实发表的,并且可以保证你发给我的东西是不会被中间人改掉的,关于更多 https 的知识可以看下我之前写过的一篇如何部署本地自签名 https 的文章,但是这篇文章不说这些内容,要将的是如何使用 Let’s Encrypt 为自己的公网域名创建可用的证书。

先说一下,我使用的环境是 CentOS 7,其他环境也是类似,所以不是 CentOS 也无需太担心。

Step 1 安装 Let’s Encrypt 的客户端

因为我使用的是 Nginx,然后 Let’s Encrypt 已经有可以直接操作 Nginx 的工具客户端了,所以我们可以直接通过命令安装一下:

$ sudo yum install epel-release
$ sudo yum install certbot-nginx

如果没有报错的话,就表示 certbot 这个工具已经在你的机器中正常安装啦!

Step 2 设置 Nginx

其实就是在 Nginx 上设置上你的域名,因为 https 是针对你的域名来生成的,所以必须让 certbot 知道你的域名,操作方式就是:

$ yum install -y nginx
$ systemctl start nginx
$ vi /etc/nginx/nginx.conf

然后找到 server_name 这一段,修改值为你的域名,例如我的配置:

修改完之后,记得保存哦,然后再让 Nginx 重新加载一遍配置: systemctl reload nginx

Step 3 获取认证

通过 certbot 我们可以很简单的获取认证,根据下面的步骤来:

$ certbot --nginx -d liqiang.io -d www.liqiang.io

如果你是首次运行的话,可能会需要你输入你的邮箱帐号,以及同意协议,然后 certbot 就会和 Let’s Encrypt 进行通信,从而开始证书创建工作了。完成之后,certbot 会智能得问你是否要开启全站 https:

Output
Please choose whether HTTPS access is required or optional.
-------------------------------------------------------------------------------
1: Easy - Allow both HTTP and HTTPS access to these sites
2: Secure - Make all requests redirect to secure HTTPS access
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):

你可以根据你的需要给出你的回答(我是推荐开启全站 https 的,即输入 2),然后 certbot 会根据你的回答帮助你设置 nginx 的配置。然后,当你看到下面这个场景的时候就表示你已经成功设置 https 了:

Output
IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at
   /etc/letsencrypt/live/example.com/fullchain.pem. Your cert will
   expire on 2017-10-23. To obtain a new or tweaked version of this
   certificate in the future, simply run certbot again with the
   "certonly" option. To non-interactively renew *all* of your
   certificates, run "certbot renew"
 - Your account credentials have been saved in your Certbot
   configuration directory at /etc/letsencrypt. You should make a
   secure backup of this folder now. This configuration directory will
   also contain certificates and private keys obtained by Certbot so
   making regular backups of this folder is ideal.
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

Step 4 开启自动续期

因为 Let’s Encrypt 每次只会给你 3 个月的有效期,所以你最多没 3 个月都需要续期一次,所以为了减少麻烦,我们可以添加一个定时任务,每个月自动更新一下证书,设置如下:

$ crontab -e
15 3 1 * * /usr/bin/certbot renew --quiet

这段的意思就是每月 1 号的早上 3:15 都会自动得向 Let’s Encrypt 续期一次,这样我们就不用担心证书过期的问题了。

Reference

  1. How To Secure Nginx with Let’s Encrypt on CentOS 7