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

[TOC]php

1、背景知识

1.一、http 和 https 是什么?

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

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

1.二、SSL/TLS 是什么?

“ HTTP over SSL/TLS ”字面意思就是带”安全套接层”的 http 协议,心里纯洁的同窗也能够理解为“带安全套的 http ”,由于带了安全套,因此固然会比较安全。其中 SSL 是“ Secure Sockets Layer ” 的缩写,是“安全套接层”的意思。 TLS 是 “Transport Layer Security” 的缩写,是 ” 传输层安全协议 ” 的意思。 SSL 和 TLS 是同一个东西的不一样阶段,理解为同一个东西也行,都是安全协议就对了。python

1.三、为何要部署 https?

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

1.四、怎么部署 https 呢?

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

1.五、怎么得到 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 安全证书,而且将它部署在本身的网站服务器上呢?这就是这篇文章要讲的内容了。git

2、Let’s Encrypt 及 Certbot 简介

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

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

2.一、Authenticators 和 Installers

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

2.二、plugin 说明

下面列举几个经常使用的 plugin 做简要说明:

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

2.三、安装 certbot

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

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

yum install certbot python2-certbot-nginx

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

3.一、生成证书

咱们在使用 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.二、配置证书

目前已经自动帮咱们配置证书了,咱们能够看下配置的形式,后续能够本身配置。

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.三、更新证书

既然已经按照好了,咱们能够查看一下证书的安装状况。

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

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

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

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

4、Certbot Webroot 模式配置证书

这里我不想使用CertBot的standalone模式,这个模式虽然能够配置好服务器,可是之后Renew的时候,须要让服务中止一下,再启动。所以抛弃这个模式,咱们使用Webroot配置模式。

由于,CertBot在验证服务器域名的时候,会生成一个随机文件,而后CertBot的服务器会经过HTTP访问你的这个文件,所以要确保你的Nginx配置好,以即可以访问到这个文件。

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

4.一、配置虚拟主机

咱们使用的 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.二、申请证书

[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.三、配置证书

生成的证书位置以下:

[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;
}

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;
}

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

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

由此咱们也能够看出,同一个 IP 的服务器能够为多个域名同时作 https。

最后祝愿咱们全部的站点都升级为 https,让 https 人人均可以用得起。

相关文章
相关标签/搜索