使用Let’s Encrypt给网站加上免费HTTPS证书

之前我用的是startssl.com家的证书,参考之前的文章《Nginx配置SSL证书》,不过最近chrome已经不信任他们的证书了,所以换了Let’s Encrypt提供的免费证书。

官方网站:https://letsencrypt.org/,部署起来很方便,使用他们提供的自动化脚本 certbot,参考 https://certbot.eff.org/。

我采用的是 certbot 的手动模式,只生成相应的证书文件,nginx配置文件是我手动修改的,参考文档:https://certbot.eff.org/docs/using.html#manual

在Ubuntu中安装certbot:

$ sudo apt-get update
$ sudo apt-get install software-properties-common
$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install python-certbot-nginx 

然后使用manual模式生成证书文件:

sudo certbot certonly --manual

接下来按照提示输入联系人的邮箱,然后需要认证的域名,再按要求配置好验证域名所有权的url。

验证邮箱:

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): 

输入域名:

Please enter in your domain name(s) (comma and/or space separated)  (Enter 'c'
to cancel):

要求配置访问路径来验证域名所有权:

Create a file containing just this data:

omN85Bt3yGVVlSgguGBmO......

And make it available on your web server at this URL:

http://kyle.ai/.well-known/acme-challenge/omN8uZRHsf3.......S58s

-------------------------------------------------------------------------------
Press Enter to Continue

等验证完域名后,证书就生成成功了

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/kyle.ai/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/kyle.ai/privkey.pem
   Your cert will expire on 2017-12-19. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot
   again. To non-interactively renew *all* of your certificates, run
   "certbot renew"

生成的域名证书有效期只有3个月,所以最好每天都用命令行来续期

crontab -e 后添加一条:

25 * * * * certbot renew

如果renew命令过程遇到如下报错:

Cert is due for renewal, auto-renewing...
Could not choose appropriate plugin: The manual plugin is not working; there may be problems with your existing configuration.
The error was: PluginError('An authentication script must be provided with --manual-auth-hook when using the manual plugin non-interactively.',)
Attempting to renew cert (blog.zengrong.net) from /etc/letsencrypt/renewal/blog.zengrong.net.conf produced an unexpected error: The manual plugin is not working; there may be problems with your existing configuration.
The error was: PluginError('An authentication script must be provided with --manual-auth-hook when using the manual plugin non-interactively.',). Skipping.

则可通过如下命令手动进行域名所有权的认证:

certbot certonly --debug --force-renew -a manual -d kyle.ai

Nginx配置的话,在server节点添加几行,示例:

listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/kyle.ai/cert.pem;
ssl_certificate_key /etc/letsencrypt/live/kyle.ai/privkey.pem;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
add_header X-Frame-Options SAMEORIGIN;
add_header Strict-Transport-Security "max-age=8640000;";
add_header X-Content-Type-Options: nosniff;