通过 Nginx 的 Gize 模块拦截请求,并且对相应的资源进行压缩,已达到减少文件体积加快文件访问速度的目的,使用 Nginx 的 Gizp 模块不需要重新编译,直接开启即可。
基本配置
在 server 中加入如下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 6;
gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml;
gzip_disable "MSIE [1-6]\.";
gzip_vary on;
|
查看效果
在 response headers
中的 Content-Encoding
是 gzip
就代表开启成功

前后对比
未开启 Gzip 的文件大小与加载速度

开启 Gzip 后的文件大小与加载速度

前后速度提升明显
完整配置
附上完整的 Nginx https + Gzip 配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| server { listen 443 ssl http2; server_name el-admin.xin www.el-admin.xin;
ssl_certificate /etc/nginx/cert/el-admin-xin/el-admin.xin_chain.crt; ssl_certificate_key /etc/nginx/cert/el-admin-xin/el-admin.xin_key.key;
ssl_dhparam /etc/nginx/cert/el-admin-xin/dhparam.pem;
ssl_stapling on; ssl_stapling_verify on;
add_header Strict-Transport-Security "max-age=63072000;" always;
ssl_prefer_server_ciphers on; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384; ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3; ssl_session_tickets on; ssl_session_cache shared:SSL:10m; ssl_session_timeout 1d; keepalive_timeout 70; add_header X-Frame-Options DENY;
gzip on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_comp_level 4; gzip_types text/css text/javascript application/javascript; gzip_disable "MSIE [1-6]\."; gzip_vary on; location / { root /usr/share/nginx/html/eladmin/dist; index index.html; try_files $uri $uri/ @router; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location @router { rewrite ^.*$ /index.html last; } }
server { listen 80; server_name el-admin.xin; return 301 https://el-admin.xin$request_uri; }
|