给你的网站加上https

文章目录

如今网络安全越来越重要了,各大浏览器已经开始限制用户访问非https网站了,如果你的网站现在还没配置支持https,那么你的访问量将极大受到影响。

说起https,最让人头痛的就是要申请证书和生成公钥和秘钥,如今,随着科技的发展,这些繁琐的事情都成为过去,今天我就来为大家介绍最简便和免费的方法。

首先,你得有一个网站服务器和域名,网站我们使用nginx提供http/https服务,https证书我们使用Let’s encrypt提供的免费证书,这个证书有效期为90天,所以我们需要定时去renew这个证书确保他有效。

在Debian 9下,我们先su root到root管理员权限下安装nginx

$ sudo apt update
$ apt install nginx

随后安装Certbot’s Nginx包,这个包会自动帮我们获取指定域名的证书,还会自动帮我们配置好nginx的ssl证书部分,具体后面会介绍。
$ apt install python-certbot-nginx -t stretch-backports

修改nginx配置文件example.com为你的网站域名。

$ vi /etc/nginx/sites-available/example.com
$ ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
$ nginx -t
$ systemctl restart nginx

nginx配置文件示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80;
listen [::]:80;

root /var/www/example.com/html;
index index.html index.htm index.nginx-debian.html;

server_name example.com www.example.com;

location / {
try_files $uri $uri/ =404;
}
}

调用certbot命令申请和安装配置证书

$ sudo certbot --nginx -d example.com -d www.example.com

期间会有选项需要你选择,下面是选择是否如果用户通过http协议访问网站自动跳转到https协议,输入2加入自动跳转配置。

1
2
3
4
5
6
7
8
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
IMPORTANT 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 2018-07-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

Let’s Encrypt证书只在90天内有效,certbot已经帮我们加入定时任务在适当的时候更新证书防止证书过期。

我们可以运行以下命令测试证书更新是否正常:

$ sudo certbot renew --dry-run

参考自: How To Secure Nginx with Let’s Encrypt on Debian 9

分享到 评论