50 Nginx的Gzip模块配置指令(一)
50 Nginx的Gzip模块配置指令(一)
50.1 未压缩文件
下面指令来自 ngx_http_gzip_module 模块,该模块在 nginx 安装时内置到 nginx 安装环境中,可以直接使用
官网模块文档介绍:https://nginx.org/en/docs/http/ngx_http_gzip_module.html
[root@nginx-100 /usr/local/nginx/conf]# ls -ltr ../html/ total 256 -rw-r--r-- 1 root root 643 Mar 15 21:05 index.html -rw-r--r-- 1 root root 532 Mar 25 18:55 50x.html -rw-r--r-- 1 root root 30 Mar 25 18:58 welcome.html drwxr-xr-x 2 root root 20 May 13 11:01 images -rw-r--r-- 1 root root 248940 May 14 16:55 jquery.js [root@nginx-100 /usr/local/nginx/conf]# cat nginx.conf user www; worker_processes 2; error_log logs/error.log; pid logs/nginx.pid; #daemon on; # 默认on events { accept_mutex on; multi_accept on; worker_connections 1024; use epoll; } http { include mime.types; default_type application/octet-stream; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; #gzip on; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 404 /50x.html; location = /50x.html { root html; } } } [root@nginx-100 /usr/local/nginx/conf]# nginx -t && nginx -s reload nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
浏览器访问:http://10.0.0.100/jquery.js ,查看原文件大小 249KB

50.2 gzip
gzip:用于开启或关闭gzip功能
| 语法 | gzip on | off; |
| 默认值 | gzip off; |
| 位置 | http 、server 、 location |
注意:只有该指令为打开状态,下面的指令才有效果
http{ gzip on; }
50.3 gzip_types
gzip_types:根据响应页的MIME类型选择性地开启 gzip 压缩功能
| 语法 | gzip_types mime-type ...; |
| 默认值 | gzip_types text/html; |
| 位置 | http 、server 、 location |
根据查看的类型压缩:application/javascript

[root@nginx-100 /usr/local/nginx/conf]# cat nginx.conf user www; worker_processes 2; error_log logs/error.log; pid logs/nginx.pid; #daemon on; # 默认on events { accept_mutex on; multi_accept on; worker_connections 1024; use epoll; } http { include mime.types; default_type application/octet-stream; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; gzip on; gzip_types application/javascript; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 404 /50x.html; location = /50x.html { root html; } } } [root@nginx-100 /usr/local/nginx/conf]# nginx -t && nginx -s reload nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
浏览器访问:http://10.0.0.100/jquery.js ,查看压缩后文件大小 31.4KB

注意:1.gzip_types 后面压缩的类型,可以通过 mime.types 文件查看
2.gzip_types *; 为压缩所有类型文件,生产不建议,有些资源已经高度压缩,再开启会浪费cpu资源
———————————————————————————————————————————————————————————————————————————
无敌小马爱学习
浙公网安备 33010602011771号