Nginx開啓http2訪問和gzip網頁壓縮功能

enter image description here

準備工做

  若是Nginx要開啓http2須要知足如下2個條件:javascript

  • nginx >=1.9.5
  • openSSL >= 1.0.2
    因此這裏咱們首先要檢查Nginx的版本若是沒有安裝要先安裝Nginx
##更新源
sudo apt-get update
##安裝nginx
sudo apt-get install nginx
##查看Nginx版本
nginx -v

若是上面的當前服務器上的nginx版本大於1.9.5。說明能夠完美的支持http2。若是小於1.9.5請先升級,nginx官網 .這裏提示一下Ubuntu 16.04.1版本默認安裝的nginx版本是1.10.3能夠完美支持http2。css

修改配置文件開啓http2

  因爲http2須要ssl證書的支持。咱們能夠申請免費的ssl證書。能夠參考我以前的文章免費ssl證書申請html

##編輯配置文件
vi /etc/nginx/sites-enabled/default

新增如下配置java

server {
            listen 443 http2;#注意這個裏的http2
            server_name test.com;#替換本身的域名
            root html;
            index index.html index.htm;
            ssl on;
            ssl_certificate /home/ubuntu/ssl/test.crt;#替換本身的證書
            ssl_certificate_key /home/ubuntu/ssl/test.com.key;#替換本身的證書
            ssl_session_timeout 5m;
            ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
            ssl_ciphers "HIGH:!aNULL:!MD5 or HIGH:!aNULL:!MD5:!3DES";
            ssl_prefer_server_ciphers on;
            location / {
                    try_files $uri $uri/ =404;
            } }

記得本身修然server_name和對應證書位置。而後保存nginx

##從新加載配置文件
sudo nginx -s reload

也能夠增長如下配置, 讓全部http請求自動跳轉到httpsweb

server {  
    listen  80;  
    server_name test.com;  
    rewrite ^(.*)$  https://$host$1 permanent;  
}

而後使用chrome先打開本身網站。而後輸入chrome://net-internals/#http2
若是列表上面有顯示你的網站說明http2已經開啓。
enter image description herechrome

開啓gzip壓縮功能

##編輯配置文件
vi /etc/nginx/nginx.conf

這個時候你會看到如下配置
enter image description here
咱們主要把圖中紅框部分註釋放開就能夠了。下面是配置json

gzip on;#是否開啓gzip
        gzip_disable "msie6";#(IE5.5和IE6 SP1使用msie6參數來禁止gzip壓縮 )指定哪些不須要gzip壓縮的瀏覽器(將和User-Agents進行匹配),依賴於PCRE庫
        gzip_vary on;#啓用應答頭"Vary: Accept-Encoding"
        gzip_proxied any;
        gzip_comp_level 6;# gzip壓縮比/壓縮級別,壓縮級別 1-9,級別越高壓縮率越大,固然壓縮時間也就越長(傳輸快但比較消耗cpu)。
        gzip_buffers 16 8k;# 設置系統獲取幾個單位的緩存用於存儲gzip的壓縮結果數據流。 例如 4 4k 表明以4k爲單位,按照原始數據大小以4k爲單位的4倍申請內存。 4 8k 表明以8k爲單位,按照原始數據大小以8k爲單位的4倍申請內存。
        gzip_http_version 1.1;#識別http協議的版本,早起瀏覽器可能不支持gzip自解壓,用戶會看到亂碼
        gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;#匹配壓縮類型

重啓以後驗證ubuntu

##後面地址能夠換成具體的資源
curl -I -H "Accept-Encoding: gzip, deflate" "https://sheeplovewolf.com/"
HTTP/1.1 200 OK
Server: nginx/1.10.3 (Ubuntu)
Date: Wed, 04 Jul 2018 05:01:47 GMT
Content-Type: text/html
Last-Modified: Tue, 31 Jan 2017 15:01:11 GMT
Connection: keep-alive
ETag: W/"5890a6b7-264"
Content-Encoding: gzip

若是返回Content-Encoding: gzip說明gzip已經開始。到此服務已經開起了http2和gzip。這樣可讓你web應用訪問速度提高一個檔次。瀏覽器

相關文章
相關標籤/搜索