openresty 部署 https 并开启 http2 支持

这里分两步介绍,第一部是配置 https , 第二步是开启 http2 支持。事实上开启 http2 支持,必须配置站点使用 https 传输协议。

HTTPS

为站点部署开启 HTTPS 支持,需要一个可信任的第三方 SSL 证书,然后针对不同的服务器环境进行配置。

我选择使用Certbot来部署一个免费、可自动更新的由Let’s Encrypt提供的期限为 90 天的权威可信任证书。Certbot官网根据不同的服务器环境提供了不同的部署方法,我使用 ubuntu + openresty(nginx) ,根据官网介绍部署方式如下:

  1. 安装 certbot(或者通过源码安装certbot
$ sudo apt-get update
$ sudo apt-get install python-software-properties software-properties-common
$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install certbot
  1. 获得证书
$ certbot(or path/certbot-auto) certonly --webroot -w /path/your-web-root -d your-domain.com -d www.your-domain.com

执行上述代码后,会在系统的/etc/letsencrypt/live目录下生成以your-domain.com的目录,里面会生成cert.pem``chain.pem``fullchain.pem``privkey.pem``README几个文件接下来在 nginx 配置文件中需要用到fullchain.pem``privkey.pem两个文件,这有关SSL证书链的概念,超出本文叙述范围。
3. 配置 nginx,在 server 中与 https 相关的配置如下

server {
   ...
   listen 443 ssl;
   ssl on;
   ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
   ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;

   ssl_session_cache shared:le_nginx_SSL:1m;
   ssl_session_timeout 1440m;

   ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
   ssl_ciphers RC4:HIGH:!aNULL:!MD5;
   ssl_prefer_server_ciphers on;
   ...
}
  1. 执行nginx -t测试 nginx 配置是否正确,确认无误后,重启 nginx 服务。
  2. 设置证书自动更新。
    上文说过Let’s Encrypt提供的免费证书期限为 90 天,certbot 提供了证书自动更新服务,通过源码安装则需要进行一些配置(配置系统的定时任务)。
    1. (Ubuntu) 在/var/spool/cron/crontabs/root文件中添加以下配置:
    0 0 * * * root /path/certbot-auto renew --quiet --no-self-upgrade
    1. 使用certbot renew --dry-run命令测试是否配置成功。

HTTP2

配置好 HTTPS 后开启 HTTP2 比较简单,两步即可完成。

  1. 重新编译openresty加入--with-http_v2_module --with-http_ssl_module选项,替换系统中使用的nginx执行文件:
./configure --with-http_v2_module --with-http_ssl_module
make // 不要 make install

关闭 nginx,使用编译生成的/resources/openresty-1.11.2.2/build/nginx-1.11.2/objs/nginx文件替换系统正使用的/usr/local/openresty/nginx/sbin/nginx文件,重启 nginx 即可。
2. 修改 nginx 配置。在 listen 后添加 http2 ,如下所示:

server {
   ...
   listen 443 ssl http2;
   ...
}

如果一开始就开启了 nginx 的 h2 模块,就不需要第一步了。至此,配置 https 并开启 http2 完成。


评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注