2018年2月

HTTP/2 - 安装部署

本文讲述如何部署 HTTPS 和 HTTP2, 后续会再整理其他相关理论, 如 HTTP/2 的好处, HTTP/2 与 HTTPS 的关系, 从 HTTP/1.1 升级到 HTTP/2 有什么要注意的, HTTP/2 为什么不叫 HTTP/2.0

环境

Ubuntu 16.04, nginx 1.12.2(安装时需要 ssl 和 http_v2 模块)

获取 SSL 证书

获取证书有多种方式, 购买(赛门铁克,也可以在国内各大云服务厂商购买), 自签名, 免费的 FreeSSL

本文说明是使用的是免费的 FreeSSL

在 FreeSSL 上根据提示操作下载得到两个文件 full_chain.pem, private.key 就是我们后面要用到的

部署 HTTPS

部署 HTTP/2 必须要先部署 https, 这里用 nginx 配置 ssl 证书, 在 nginx.conf 中添加:

server
{
    # 默认是 listen 80
    listen 443 ssl;
    ...

    # ssl https
    ssl                  on;
    ssl_certificate      /usr/local/nginx/ssl/full_chain.pem;
    ssl_certificate_key  /usr/local/nginx/ssl/private.key;
    ...
}

如果强制 http 跳转到 https, 再自己在原有 server 里加 rewrite, 验证配置文件有效后重启 nginx, 就可以使用 https 访问站点了

# 验证 nginx 配置文件
sudo nginx -t
# reload
sudo service nginx reload

配置 HTTP/2 (Nginx)

查看 nginx 是否编译了 http_v2_module 模块

➜ sudo nginx -V
nginx version: nginx/1.13.9
built by gcc 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.9)
built with OpenSSL 1.0.2l  25 May 2017
TLS SNI support enabled
configure arguments: --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module --with-ipv6 --with-http_sub_module --with-openssl=/home/jw/下载/lnmp1.4-full/src/openssl-1.0.2l

修改 nginx 配置文件, 在 https 配置里加 http2 关键字就可以了

server
{
    # 默认是 listen 80
    listen 443 ssl http2;
    ...

    # ssl https
    ssl                  on;
    ssl_certificate      /usr/local/nginx/ssl/full_chain.pem;
    ssl_certificate_key  /usr/local/nginx/ssl/private.key;
    ...
}

重启 nginx 就可以了, 更多关于 nginx http2 的详细配置

验证

建议安装 chrome 的扩展 HTTP/2 and SPDY indicator 方便查看, 当你浏览的网页是 HTTP/2 的时候, 闪电图标直接亮起
chrome-ext

点击图标,查看详细
chrome-detail

打开 chrome 的调试工具, 添加上 Protocol, 能看到当前域名已经变成 h2
chrome-h2-protocol

HTTP_PUSH

最新版本的 nginx-1.13.9 已经支持 HTTP/2 Server Push