两种方式开启:

    • 服务端设置http头
    • 客户端js/html标签属性,关键字preload
    • nginx 1.13.9开始支持server push

      1. server {
      2. listen 443 ssl http2;
      3. server_name localhost;
      4. ssl on;
      5. ssl_certificate /etc/nginx/certs/example.crt;
      6. ssl_certificate_key /etc/nginx/certs/example.key;
      7. ssl_session_timeout 5m;
      8. ssl_ciphers HIGH:!aNULL:!MD5;
      9. ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
      10. ssl_prefer_server_ciphers on;
      11. location / {
      12. root /usr/share/nginx/html;
      13. index index.html index.htm;
      14. http2_push /style.css;
      15. }
      16. }

      后端实现: ```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) }

    1. Link: </styles.css>; rel=preload; as=style, </example.png>; rel=preload; as=image<br />服务器发现有这个头信息,就会进行服务器推送。
    2. ```javascript
    3. server {
    4. listen 443 ssl http2;
    5. root /var/www/html;
    6. location = / {
    7. http2_push_preload on;
    8. }
    9. }