打開 Chrome 開發者工具,如果看到網頁載入的資源(CSS、圖片、JS...),很多時間花在Queueing,
那將網站從 HTTP/1.1 升級到 HTTP/2,可大大改善網站速度。
因為 HTTP/1.0、HTTP/1.1,同一個網域只能有6個 TCP 連線(以目前的chrome為例),
所以當網頁的資源連結很多,會發生排隊阻塞的情況,載入時間累計就慢了。
以前在 HTTP/1.0、HTTP/1.1 的連線數限制下,可用 Domain sharding 的方式解決,
Domain sharding:將資源的請求,分配到不同的網域,以突破連線數的限制。
現在 HTTP/2 採用多路復用,讓資源的請求合併在同一個 TCP 連線內,可以解決排隊阻塞的情況。
HTTP/2 跟 HTTP/1.1 有高度相容性,但 HTTP/2 只能在 https 的環境執行,
所以若網站原本就用 https,或沒特殊情況須用 http,
那只須 Nginx 設定使用 https 並開啟 http2 即可。
[Nginx 開啟 HTTP/2]
先確認安裝的 nginx 有支援 HTTP/2
- nginx 版本 1.9.5 以上
(HTTP/2 Supported in Open Source NGINX 1.9.5 | NGINX) - nginx 使用的 OpenSSL 版本 1.0.2 以上
目前HTTP/2使用ALPN(Application-Layer Protocol Negotiation、一個傳輸層安全協定(TLS) 的擴充),而OpenSSL在1.0.2後開始支援ALPN
(應用層協定協商 - 維基百科,自由的百科全書) - nginx 編譯參數有開啟ngx_http_v2_module模組,--with-http_v2_module
使用「nginx -V」查看相關資訊
# nginx -V nginx version: nginx/1.18.0 built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) built with OpenSSL 1.0.2k-fips 26 Jan 2017 TLS SNI support enabled configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx ..... --with-http_v2_module .....
確定都符合後,只須在 nginx 網站設定檔上,加上「http2」即可。
例如,原本
server { ... listen 443 ssl; ... }加上「http2」,改成
server { ... listen 443 ssl http2; ... }
# systemctl reload nginx.service
[測試:HTTP/1.1、HTTP/2]
圖一:HTTP/1.1,瀏覽有2000個圖片的頁面,花7.63秒。
[其他:chrome開發者工具request時間區段說明]
圖二:HTTP/2,瀏覽有2000個圖片的頁面,花4.73秒。
- Queueing. The browser queues requests when:
There are higher priority requests.
There are already six TCP connections open for this origin, which is the limit. Applies to HTTP/1.0 and HTTP/1.1 only.
The browser is briefly allocating space in the disk cache - Stalled. The request could be stalled for any of the reasons described in Queueing.
- DNS Lookup. The browser is resolving the request's IP address.
- Initial connection. The browser is establishing a connection, including TCP handshakes/retries and negotiating an SSL.
- Proxy negotiation. The browser is negotiating the request with a proxy server.
- Request sent. The request is being sent.
- ServiceWorker Preparation. The browser is starting up the service worker.
- Request to ServiceWorker. The request is being sent to the service worker.
- Waiting (TTFB). The browser is waiting for the first byte of a response. TTFB stands for Time To First Byte. This timing includes 1 round trip of latency and the time the server took to prepare the response.
- Content Download. The browser is receiving the response.
- Receiving Push. The browser is receiving data for this response via HTTP/2 Server Push.
- Reading Push. The browser is reading the local data previously received.
參考:
沒有留言:
張貼留言