本站HTTP/2的实现

本站HTTP/2的实现

[此文成于2018年8月,自2019年3月迁徙更新后已自动支持HTTP/2。]

本站目前成功支持HTTP/2,特此记录实现过程。

HTTP/2的优势我就不再赘述了,简言之:

  • HTTP/2 is fully multiplexed, instead of ordered and blocking.
  • HTTP/2 can use one connection for parallelism.
  • HTTP/2 uses header compression to reduce overhead.
  • HTTP/2 allows servers to “push” responses proactively into client caches.
    Image
    Image

本次实现参考了一些前人的经验,具体链接附在文末。

Nginx从1.9.5开始支持HTTP/2。鉴于EPEL里的Nginx是用OpenSSL 1.01e编译的rpm(CentOS7.4后的release里才提供了最新的OpenSSL), 而支持HTTP/2需要OpenSSL 1.02以上,这意味着我们无法通过yum update一键升级,而是需要手动用OpenSSL 1.02重新编译Nginx并自行进行安装。

首先是下载最新的openssl和nginx,编译并安装。

代码如下:

wget https://www.openssl.org/source/openssl-1.0.2p.tar.gz
tar -zxvf openssl-1.0.2p.tar.gz
wget http://nginx.org/download/nginx-1.15.2.tar.gz
tar -zxvf nginx-1.13.0.tar.gz 
cd nginx-1.13.0 
./configure --with-openssl=/home/openssl-1.0.2p --with-http_v2_module --with-http_ssl_module
make
make install

需要注意的是configure时别忘了添加--with-openssl参数以及--with-http_v2_module--with-http_ssl_module,后两者是支持HTTP/2所需的模块。

之后是添加softlink,添加启动脚本,添加系统服务。

ln -s /usr/local/nginx/sbin/nginx /usr/sbin/nginx

新建启动脚本 /etc/init.d/nginx,脚本内容可以从Nginx官网例子里取得。

chmod 755 /etc/init.d/nginx

添加mime.types文件(Nginx启动失败时提示缺少此文件),于是网上随便找了一个

添加系统服务

chkconfig --add nginx
chkconfig --level 345 nginx on

最后,在ghost配置文件/etc/nginx/conf.d/ghost.conf里添加http2 参数: listen 443 ssl http2即可。

service nginx start

提示成功后可以通过chrome的开发者工具查看,也可以使用这个小工具https://tools.keycdn.com/http2-test

测试成功
image

参考文档

https://segmentfault.com/a/1190000007637735
https://www.jianshu.com/p/645e41c8dd93
https://blog.restcase.com/http2-benefits-for-rest-apis/
https://docs.nginx.com/nginx/admin-guide/installing-nginx/installing-nginx-open-source/
https://www.digitalocean.com/community/questions/how-to-get-already-installed-nginx-to-use-openssl-1-0-2-for-alpn
https://ma.ttias.be/rhel-centos-7-4-restores-http2-functionality-nginx/
https://www.digitalocean.com/community/tutorials/how-to-compile-nginx-from-source-on-a-centos-6-4-x64-vps
https://www.nginx.com/resources/wiki/start/topics/examples/redhatnginxinit/
https://tools.keycdn.com/http2-test

Subscribe to 隅

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe