HTTP2的Server Push使用方法[服务器推送资源]

什么是HTTP2 Server Push ?

HTTP2 Server Push简单来说,就是webserver不需要用户请求,直接推送文件到浏览器
服务推送是HTTP2协议的优点之一
具体介绍请参考
https://en.wikipedia.org/wiki/HTTP/2_Server_Push

如何使用启用Server Push?

   header("Link: </css/styles.css>; rel=preload; as=style", false);  //php代码
   Header set Link "</css/styles.css>; rel=preload; as=style"  //apache配置
add_header Link "<//lib/Peafowl/js/scripts.min.js>; rel=preload; as=script";  //nginx配置

利用cookie控制缓存
由于推送没有暂停功能,这里需要利用cookie防止重复推送
以nginx为例

//http段添加
http2_push_preload on;
add_header Set-Cookie "http2push=1";
add_header Link $resources;
//server段添加
http2_recv_buffer_size 512k;
map $http_cookie $resources {
    "~*http2push=1" "";
    default "</lib/Peafowl/peafowl.min.css>; rel=preload; as=style, </app/themes/Peafowl/style.min.css>; rel=preload; as=style, </lib/Peafowl/js/scripts.min.js>; rel=preload; as=script, </lib/Peafowl/peafowl.min.js>; rel=preload; as=script, </app/lib/main.min.js>; rel=preload; as=script";
}

注意:超过缓存会出错, 建议加大缓存,或者只加载css/js

本站推送的文件设置

Header set Link "</usr/themes/JiaJie/style.css>; rel=preload; as=style, </usr/plugins/TextEditor/js/Lighter/Lighter.js>; rel=preload; as=script, </usr/plugins/TextEditor/js/Lighter/mootools-yui-compressed-1.2.4.js>; rel=preload; as=script"



参考来源
https://www.nginx.com/blog/nginx-1-13-9-http2-server-push/
http://www.ruanyifeng.com/blog/2018/03/http2_server_push.html

此处评论已关闭