两种方式开启:
- 服务端设置http头
- 客户端js/html标签属性,关键字preload
nginx 1.13.9开始支持server push
server {listen 443 ssl http2;server_name localhost;ssl on;ssl_certificate /etc/nginx/certs/example.crt;ssl_certificate_key /etc/nginx/certs/example.key;ssl_session_timeout 5m;ssl_ciphers HIGH:!aNULL:!MD5;ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;ssl_prefer_server_ciphers on;location / {root /usr/share/nginx/html;index index.html index.htm;http2_push /style.css;}}
后端实现: ```javascript const http2 = require(‘http2’) const server = http2.createSecureServer( { cert, key }, onRequest )
function push (stream, filePath) { const { file, headers } = getFile(filePath) const pushHeaders = { [HTTP2_HEADER_PATH]: filePath }
stream.pushStream(pushHeaders, (pushStream) => { pushStream.respondWithFD(file, headers) }) }
function onRequest (req, res) { // Push files with index.html if (reqPath === ‘/index.html’) { push(res.stream, ‘bundle1.js’) push(res.stream, ‘bundle2.js’) }
// Serve file res.stream.respondWithFD(file.fileDescriptor, file.headers) }
Link: </styles.css>; rel=preload; as=style, </example.png>; rel=preload; as=image<br />服务器发现有这个头信息,就会进行服务器推送。```javascriptserver {listen 443 ssl http2;root /var/www/html;location = / {http2_push_preload on;}}
