一、背景知识

1.1、http 和 https 是什么?

简单来说,http 是一个传输网页内容的协议,比如你看到的 http 开头的网站 http://www.163.com ,其网页上的文字、图片、 CSS 、 JS 等文件都是通过 http 协议传输到我们的浏览器,然后被我们看到。

Nginx 通过 certbot 为网站自动配置 SSL 证书并续期

而 https 可以理解为“ HTTP over SSL/TLS ”,好端端的 http 为什么需要“ over SSL/TLS ”呢,因为 http 是明文传输的,通过 http 协议传输的内容很容易被偷看和篡改,为了安全(你肯定不想被人偷看或者篡改网页内容吧,比如网站银行密码什么的。)就为 http 协议再加上了一层 SSL/TLS 安全协议,所以就有了 https 。

1.2、SSL/TLS 是什么?

“ HTTP over SSL/TLS ”字面意思就是带”安全套接层”的 http 协议,内心纯洁的同学也可以理解为“带安全套的 http ”,因为带了安全套,所以当然会比较安全。其中 SSL 是“ Secure Sockets Layer ” 的缩写,是“安全套接层”的意思。 TLS 是 “Transport Layer Security” 的缩写,是 ” 传输层安全协议 ” 的意思。 SSL 和 TLS 是同一个东西的不同阶段,理解为同一个东西也行,都是安全协议就对了。

Nginx 通过 certbot 为网站自动配置 SSL 证书并续期

1.3、为什么要部署 https?

说到底,就是 https 更安全。甚至为了安全,一个专业可靠的网站, https 是必须的。 Firefox 和 Chrome 都计划将没有配置 SSL 加密的 http 网站标记为不安全(貌似 Firefox 50 已经这么干了),目前它们也正在联合其他相关的基金会与公司推动整个互联网 https 化,现在大家访问的一些主要的网站。如 Google 多年前就已经全部启用 https ,国内的淘宝、搜狗、知乎、百度等等也全面 https 了。甚至 Google 的搜索结果也正在给予 https 的网站更高的排名和优先收录权。

1.4、怎么部署 https 呢?

你只需要有一张被信任的 CA ( Certificate Authority )也就是证书授权中心颁发的 SSL 安全证书,并且将它部署到你的网站服务器上。一旦部署成功后,当用户访问你的网站时,浏览器会在显示的网址前加一把小绿锁,表明这个网站是安全的,当然同时你也会看到网址前的前缀变成了 https ,不再是 http 了。

Nginx 通过 certbot 为网站自动配置 SSL 证书并续期

1.5、怎么获得 SSL 安全证书呢?

理论上,我们自己也可以签发 SSL 安全证书,但是我们自己签发的安全证书不会被主流的浏览器信任,所以我们需要被信任的证书授权中心( CA )签发的安全证书。而一般的 SSL 安全证书签发服务都比较贵,比如 Godaddy 、 GlobalSign 等机构签发的证书一般都需要20美金一年甚至更贵,不过为了加快推广 https 的普及, EEF 电子前哨基金会、 Mozilla 基金会和美国密歇根大学成立了一个公益组织叫 ISRG ( Internet Security Research Group ),这个组织从 2015 年开始推出了 Let’s Encrypt 免费证书。这个免费证书不仅免费,而且还相当好用,所以我们就可以利用 Let’s Encrypt 提供的免费证书部署 https 了。那么怎么获得 Let’s Encrypt 安全证书,并且将它部署在自己的网站服务器上呢?这就是这篇文章要讲的内容了。

二、Let’s Encrypt 及 Certbot 简介

前面已经介绍过, Let’s Encrypt 是 一个叫 ISRG ( Internet Security Research Group ,互联网安全研究小组)的组织推出的免费安全证书计划。参与这个计划的组织和公司可以说是互联网顶顶重要的先驱,除了前文提到的三个牛气哄哄的发起单位外,后来又有思科(全球网络设备制造商执牛耳者)、 Akamai 加入,甚至连 Linux 基金会也加入了合作,这些大牌组织的加入保证了这个项目的可信度和可持续性。

Nginx 通过 certbot 为网站自动配置 SSL 证书并续期

后来 ISRG 的发起者 EFF (电子前哨基金会)为 Let’s Encrypt 项目发布了一个官方的客户端 Certbot ,利用它可以完全自动化的获取、部署和更新安全证书。这真是非常容易、方便呀,所以我们就可以直接使用官方客户端,不需要再使用第三方的工具了。虽然第三方工具也可以使用,但是官方工具更权威,风险也更小,而且遇到问题也更容易解决,毕竟有官方的支持。何况 Certbot 确实非常方便,也比所有的第三方工具都更方便,何乐而不用呢?

2.1、Authenticators 和 Installers

Certbot 支持两种类型的 plugin,一种是用来获取和安装证书的,成为称为 Authenticators;另外一种是用来安装证书的,称为 Installers。有的 plugin 支持一种,有的两种都支持,如 nginx。
Authenticators plugin 使用 certonly 命令来获取证书,而 Installers plugin 使用install命令来安装证书。

2.2、plugin 说明

下面列举几个常用的 plugin 作简要说明:

  • Webroot:本地有运行 webserver 并且有能力修改其配置,就可以用该种方式(创建隐藏文件.well-known),获取证书时无需暂停 webserver 的运行。
  • Standalone:服务器未运行 webserver 可以使用该方式,要保持 80 或 443 端口开放。
  • Nginx:自动获取和安装证书(自动修改配置文件)。

2.3、安装 certbot

Certbot 的官方网站是 https://certbot.eff.org/ ,打开这个链接选择自己使用的 web server 和操作系统,EFF 官方会给出详细的使用方法,以下以本网站域名( bbs.wzlinux.com )举例。

Nginx 通过 certbot 为网站自动配置 SSL 证书并续期

我们的系统环境为 CentOS 7,Web 服务器为 epel 源中的 nginx,只是为了掩饰安装证书,没有做什么网页,大家了解这个过程为主,我们使用下面命令进行安装 certbot。

yum install certbot python2-certbot-nginx

三、Certbot 为 nginx 自动获取安装证书

3.1、生成证书

我们在使用 certbot 生成证书之前,要把域名解析到当前的服务器,使用令生certbot --nginx成证书,并且会帮我们自动配置到 nginx 上面,过程中需要我们输入邮箱地址。

[root@lnmp-1 ~]# certbot --nginx
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): wangzan18@126.com
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y
Starting new HTTPS connection (1): supporters.eff.org
No names were found in your configuration files. Please enter in your domain
name(s) (comma and/or space separated)  (Enter 'c' to cancel): bbs.wzlinux.com
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for bbs.wzlinux.com
Waiting for verification...
Cleaning up challenges
Resetting dropped connection: acme-v02.api.letsencrypt.org
Deploying Certificate to VirtualHost /etc/nginx/nginx.conf

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): 2
Redirecting all traffic on port 80 to ssl in /etc/nginx/nginx.conf

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://bbs.wzlinux.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=bbs.wzlinux.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/bbs.wzlinux.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/bbs.wzlinux.com/privkey.pem
   Your cert will expire on 2019-07-25. 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

按照提示输入自己的信息即可,如果希望自己手动配置 nginx 证书,可以使用下面的命令。

certbot --nginx certonly

3.2、配置证书

目前已经自动帮我们配置证书了,我们可以看下配置的形式,后续可以自己配置。

server {
        server_name bbs.wzlinux.com;   # managed by Certbot
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/bbs.wzlinux.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/bbs.wzlinux.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

server {
    if ($host = bbs.wzlinux.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen       80 ;
    listen       [::]:80 ;
    server_name bbs.wzlinux.com;
    return 404; # managed by Certbot

}

3.3、更新证书

既然已经按照好了,我们可以查看一下证书的安装情况。

Nginx 通过 certbot 为网站自动配置 SSL 证书并续期
Nginx 通过 certbot 为网站自动配置 SSL 证书并续期

出于安全策略, Let’s Encrypt 签发的证书有效期只有 90 天,所以需要每隔三个月就要更新一次安全证书,虽然有点麻烦,但是为了网络安全,这是值得的也是应该的。好在 Certbot 也提供了很方便的更新方法。
我们可以在 www.ssllabs.com 测试证书是否正常。

Nginx 通过 certbot 为网站自动配置 SSL 证书并续期

  • 测试一下更新,这一步没有在真的更新,只是在调用 Certbot 进行测试。
certbot renew --dry-run

建议在服务器上面添加一个定时任务,让服务器定时请求进行更新。

0 0,12 * * * python -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew

四、Certbot Webroot 模式配置证书

这里我不想使用CertBot的standalone模式,这个模式虽然可以配置好服务器,但是以后Renew的时候,需要让服务停止一下,再启动。因此抛弃这个模式,我们使用Webroot配置模式。

因为,CertBot在验证服务器域名的时候,会生成一个随机文件,然后CertBot的服务器会通过HTTP访问你的这个文件,因此要确保你的Nginx配置好,以便可以访问到这个文件。

我这里的 web 服务器使用 LNMP 一键安装包来安装的,我们之间为 其中的 nginx 配置证书,首先我们先生成证书。

4.1、配置虚拟主机

我们使用的 lnmp 一键安装包进行安装的,我们可以直接使用命令 lnmp vhost add命令添加我们需要的主机。

[root@test ~]# lnmp vhost add
+-------------------------------------------+
|    Manager for LNMP, Written by Licess    |
+-------------------------------------------+
|              https://lnmp.org             |
+-------------------------------------------+
Please enter domain(example: www.lnmp.org): bbs1.wzlinux.com
 Your domain: bbs1.wzlinux.com
Enter more domain name(example: lnmp.org *.lnmp.org): 
Please enter the directory for the domain: bbs1.wzlinux.com
Default directory: /home/wwwroot/bbs1.wzlinux.com: 
Virtual Host Directory: /home/wwwroot/bbs1.wzlinux.com
Allow access log? (y/n) 
Disable access log.
Please enter Administrator Email Address: 
Administrator Email Address will set to webmaster@example.com!
Create database and MySQL user with same name (y/n) 
Add SSL Certificate (y/n) n

Press any key to start create virtul host...

Create Virtul Host directory......
set permissions of Virtual Host directory......
Test Nginx configure file......
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

Reload Nginx......
Test Apache configure file...
test apache configure... Syntax OK
 done
Restart Apache...
graceful apache...  done
================================================
Virtualhost infomation:
Your domain: bbs1.wzlinux.com
Home Directory: /home/wwwroot/bbs1.wzlinux.com
Enable log: yes
Create database: no
Create ftp account: no
================================================

4.2、申请证书

[root@test ~]# certbot certonly --webroot -w /home/wwwroot/bbs1.wzlinux.com/ -d bbs1.wzlinux.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator webroot, Installer None
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): wangzan18@126.com
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y
Starting new HTTPS connection (1): supporters.eff.org
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for bbs1.wzlinux.com
Using the webroot path /home/wwwroot/bbs1.wzlinux.com for all unmatched domains.
Waiting for verification...
Cleaning up challenges
Resetting dropped connection: acme-v02.api.letsencrypt.org

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/bbs1.wzlinux.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/bbs1.wzlinux.com/privkey.pem
   Your cert will expire on 2019-08-06. 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"
 - 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

4.3、配置证书

生成的证书位置如下:

[root@test ~]# ll /etc/letsencrypt/live/bbs1.wzlinux.com/
total 4
lrwxrwxrwx. 1 root root  40 May  8 18:50 cert.pem -> ../../archive/bbs1.wzlinux.com/cert1.pem
lrwxrwxrwx. 1 root root  41 May  8 18:50 chain.pem -> ../../archive/bbs1.wzlinux.com/chain1.pem
lrwxrwxrwx. 1 root root  45 May  8 18:50 fullchain.pem -> ../../archive/bbs1.wzlinux.com/fullchain1.pem
lrwxrwxrwx. 1 root root  43 May  8 18:50 privkey.pem -> ../../archive/bbs1.wzlinux.com/privkey1.pem
-rw-r--r--. 1 root root 692 May  8 18:50 README

目前生成的 nginx 配置文件/usr/local/nginx/conf/vhost/bbs1.wzlinux.com.conf如下:

server
    {
        listen 80;
        #listen [::]:80;
        server_name bbs1.wzlinux.com ;
        index index.html index.htm index.php default.html default.htm default.php;
        root  /home/wwwroot/bbs1.wzlinux.com;

        #error_page   404   /404.html;

        # Deny access to PHP files in specific directory
        #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; }

        include proxy-pass-php.conf;

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires      30d;
        }

        location ~ .*\.(js|css)?$
        {
            expires      12h;
        }

        location ~ /.well-known {
            allow all;
        }

        location ~ /\.
        {
            deny all;
        }

        access_log off;
    }

然后我们为其添加 SSL 证书,修改后的配置文件如下:

server
        {
        listen 443 ssl http2;
        #listen [::]:443 ssl http2;
        server_name     bbs1.wzlinux.com;
        index index.html index.htm index.php default.html default.htm default.php;
        root  /home/wwwroot/bbs1.wzlinux.com;
        ssl on;
        ssl_certificate /etc/letsencrypt/live/bbs1.wzlinux.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/bbs1.wzlinux.com/privkey.pem;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5";
        ssl_session_cache builtin:1000 shared:SSL:10m;
        # openssl dhparam -out /usr/local/nginx/ssl/dhparam.pem 2048
        #ssl_dhparam /usr/local/nginx/ssl/dhparam.pem;

        #error_page   404   /404.html;

        # Deny access to PHP files in specific directory
        #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; }

        include enable-php.conf;

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires      30d;
        }

        location ~ .*\.(js|css)?$
        {
            expires      12h;
        }

        location ~ /.well-known {
            allow all;
        }

        location ~ /\.
        {
            deny all;
        }

        access_log  off;
}

server
        {
        listen          80;
        server_name bbs1.wzlinux.com;
        return 301 https://$server_name$request_uri;
}

Nginx 通过 certbot 为网站自动配置 SSL 证书并续期

4.4 配置站点 bbs2

在做一个bbs2.wzlinux.com,同样的做法去生成证书。

[root@test bbs2.wzlinux.com]# certbot certonly --webroot -w /home/wwwroot/bbs2.wzlinux.com/ -d bbs2.wzlinux.com --email wangzan18@126.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator webroot, Installer None
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for bbs2.wzlinux.com
Using the webroot path /home/wwwroot/bbs2.wzlinux.com for all unmatched domains.
Waiting for verification...
Cleaning up challenges
Resetting dropped connection: acme-v02.api.letsencrypt.org

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/bbs2.wzlinux.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/bbs2.wzlinux.com/privkey.pem
   Your cert will expire on 2019-08-06. 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"
 - 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

配置后的 nginx 配置文件内容为:

server
        {
        listen 443 ssl http2;
        #listen [::]:443 ssl http2;
        server_name     bbs2.wzlinux.com;
        index index.html index.htm index.php default.html default.htm default.php;
        root  /home/wwwroot/bbs2.wzlinux.com;
        ssl on;
        ssl_certificate /etc/letsencrypt/live/bbs2.wzlinux.com/fullchain.pem;     
        ssl_certificate_key /etc/letsencrypt/live/bbs2.wzlinux.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/bbs2.wzlinux.com/chain.pem;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5";
        ssl_session_cache builtin:1000 shared:SSL:10m;
        # openssl dhparam -out /usr/local/nginx/ssl/dhparam.pem 2048
        #ssl_dhparam /usr/local/nginx/ssl/dhparam.pem;

        #error_page   404   /404.html;

        # Deny access to PHP files in specific directory
        #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; }

        include enable-php.conf;

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires      30d;
        }

        location ~ .*\.(js|css)?$
        {
            expires      12h;
        }

        location ~ /.well-known {
            allow all;
        }

        location ~ /\.
        {
            deny all;
        }

        access_log  off;
}

server
        {
        listen          80;
        server_name bbs2.wzlinux.com;
        return 301 https://$server_name$request_uri;
}

Nginx 通过 certbot 为网站自动配置 SSL 证书并续期

最后我们给服务器添加一个定时任务。

0 3 */7 * * /bin/certbot renew --force-renew --disable-hook-validation --renew-hook "/etc/init.d/nginx reload"

由此我们也可以看出,同一个 IP 的服务器可以为多个域名同时做 https。

最后祝愿我们所有的站点都升级为 https,让 https 人人都可以用得起。