为网站安装SSL证书可以加密流量,保护数据的安全,本教程使用Let’s Encrypt提供的认证服务为网站安装免费的SSL证书,开启Https访问,以Ubuntu18.04为例。
我们使用Certbot来安装证书,它可以简化证书生成步骤并定时更新证书,十分方便。
安装之前
Ubuntu自带了ufw防火墙,根据服务器提供商的不同会默认打开或关闭,我们首先需要确认ufw的状态。
查看防火墙状态,
$ ufw status
关闭或开启防火墙
# 开启
$ sudo ufw enable
# 关闭
$ sudo ufw disable
关闭防火墙的话可以直接看下一章了,如果想保持开启的话那么需要把443端口处的服务打开,先查看有哪些应用可以开启,
$ ufw app list
# Output
Available applications:
OpenSSH
Nginx Full
Nginx HTTP
Nginx HTTPS
...
放行443和80端口,
$ sudo ufw allow 'Nginx Full'
别忘了把OpenSSH也加进去,不然ssh连不上了。
$ sudo ufw allow OpenSSH
# 如果ssh端口不在22
$ sudo ufw allow xx(端口号)
安装Certbot
添加库,
$ sudo add-apt-repository ppa:certbot/certbot
安装Certbot,
$ sudo apt install python-certbot-nginx
安装SSL证书
$ sudo certbot --nginx -d example.com -d www.example.com
输入自己的邮箱,一路yes下去,稍等片刻后会问你选择哪个配置,
# Output
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):
选择1则需要自己配置Nginx来开启https,选择2会自动陪你配置并将http全部重定向至https,为了方便选2就行。
输出以下信息表示成功安装SSL证书,现在可以打开网站试试效果了~
OutputIMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/example.com/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/example.com/privkey.pem
Your cert will expire on 2020-09-06. 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
自动更新证书
一般来说证书有效期为三个月,之后需要更新,不过我们之前安装的脚本已经为我们开启了自动更新,输入
$ sudo certbot renew --dry-run
如果没有发生错误则表示自动更新程序运行正常,我们就不用担心证书过期的问题了~