HTTP 2.0超文本传输协议 2.0,是下一代HTTP协议,比目前普遍使用的HTTP1.1更先进,经过测试开启HTTP2.0能给网站尤其是SSL加密的网站提供更高的速度和稳定性。

Nginx 1.9.0 以上的版本就开始支持HTTP2.0技术,通过新增了 http_v2_module 模块用于提供 HTTP/2 服务.

虽然http2.0有HTTP/2 Cleartext可以通过非加密通道传输,但目前支持的浏览器很少,因此如果现在想进行实用的部署,HTTP2.0还是需要SSL的支持,通过开启HTTPS加密通道来支持HTTP2.0,SSL目前有 Let’s Encrypt 的免费证书可以使用,因此个人站长在使用中完全不需要有压力。

言归正传,接下来介绍如何配置nginx下的http2.0

目前默认编译Nginx是不包含Http2模块的,后续会不会加入默认参数暂时还不知道,因此可以在编译安装之前查看一下Nginx的编译选项

#./nginx -V
nginx version: nginx/1.9.15
built by gcc 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4)
built with OpenSSL 1.0.2g  1 Mar 2016
TLS SNI support enabled
configure arguments: --prefix=/home/bnxbcom/software/nginx --with-openssl=/home/bnxbcom/Downloads/nginx/openssl-1.0.2g --with-pcre=/home/bnxbcom/Downloads/nginx/pcre-8.38 --with-zlib=/home/bnxbcom/Downloads/nginx/zlib-1.2.8 --with-http_ssl_module --with-threads --with-debug

可以看到,没有HTTP2的选项,这里需要启用http2支持

修改编译选项

在configure的选项中加入--with-http_v2_module,由于HTTP2需要SSL的支持,因此如缺少--with-http_ssl_module选项,还需要加入--with-http_ssl_module。 如下:

./configure --prefix=/home/bnxbcom/software/nginx \
--with-openssl=/home/bnxbcom/Downloads/nginx/openssl-1.0.2g \
--with-pcre=/home/bnxbcom/Downloads/nginx/pcre-8.38 \
--with-zlib=/home/bnxbcom/Downloads/nginx/zlib-1.2.8 \
--with-http_ssl_module \
--with-threads \
--with-debug \
--with-http_v2_module

编译&升级

make & make install

修改虚拟机的配置文件,启用HTTP2,如下:

server {
listen 443 ssl http2 default_server;
server_name www.bnxb.com;
ssl_certificate /path/to/public.crt;
ssl_certificate_key /path/to/private.key;

记得将本站的域名换成你自己的

验证配置文件,通过 /usr/local/nginx/sbin/nginx -t 或者 nginx -t 来检测是否配置正确,然后重启 Nginx ,即可。

#./nginx -t
nginx: the configuration file /home/bnxbcom/software/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /home/bnxbcom/software/nginx/conf/nginx.conf test is successful

启动nginx

#./nginx

验证HTTP2是否已启用

方法一

使用高版本如56.0.2924.87的Chrome,按照如下步骤操作

使用Chrome访问启用http2的站点,也就是你自己配置后的域名。

新开TAB页,在地址栏中输入chrome://net-internals/#http2,检查HTTP/2 sessions下的表格。

确认表格里是否出现了上一步访问的主机地址

方法二

使用curl命令,参考HTTP/2 with curl,执行如下命令,确认站点返回的协议是否为HTTP

curl --http2 -I www.bnxb.com

如执行上述命令时遇到如下错误,说明系统当前安装的curl还不支持HTTP2协议。

curl https://www.bnxb.com/ --http2
curl: (1) Unsupported protocol

可以执行如下命令,检查系统当前安装的curl支持的特性列表,确认是否包含HTTP2。

curl -V
curl 7.47.0 (i686-pc-linux-gnu) libcurl/7.47.0 GnuTLS/3.4.10 zlib/1.2.8 libidn/1.32 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp smb smbs smtp smtps telnet tftp