如何在Nginx网络服务器上启用gzip

How to enable gzip on a Nginx web server?

本文关键字:服务器 启用 gzip 网络服务 网络 Nginx      更新时间:2023-09-26

我试图在我的网站上启用gzip,但结果并不好。使用进行检查http://checkgzipcompression.com/gzip显示已启用,但当我转到https://gtmetrix.com/为了测试我的网站的性能和速度,有些文件(例如JavaScript文件和SVG文件)似乎没有启用gzip。

我做错了什么?

为了启用gzip,我使用了.htaccess并粘贴了以下代码:

<IfModule mod_mime.c>
   AddEncoding gzip svgz
</IfModule>
<IfModule mod_deflate.c>
  # Compress HTML, CSS, JavaScript, Text
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
</IfModule>

mod_deflate.c之前,我也尝试过以下代码:

<ifModule mod_gzip.c>
  mod_gzip_on Yes
  mod_gzip_dechunk Yes
  mod_gzip_item_include file '.(html?|txt|css|js|php|pl)$
  mod_gzip_item_include mime ^application/x-javascript.*
  mod_gzip_item_include mime ^text/.*
  mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
  mod_gzip_item_exclude mime ^image/.* 
  mod_gzip_item_include handler ^cgi-script$
</ifModule>

服务器信息

server  nginx
vary    Accept-Encoding

NGINX不支持.htaccess文件。

类似Apache:.htaccess

你不能这样做。你不应该。如果你需要.htaccess,你可能是做错了。

为了在NGINX web服务器上启用Gzip压缩,请首先打开NGINX的默认配置文件:sudo vim /etc/nginx/nginx.conf,并用以下内容替换现有的Gzip设置:

nginx.conf (您可以根据需要修改下面的设置)

  # Enable Gzip
  gzip  on;
  gzip_http_version 1.0;
  gzip_comp_level 2;
  gzip_min_length 1100;
  gzip_buffers     4 8k;
  gzip_proxied any;
  gzip_types
    # text/html is always compressed by HttpGzipModule
    text/css
    text/javascript
    text/xml
    text/plain
    text/x-component
    application/javascript
    application/json
    application/xml
    application/rss+xml
    font/truetype
    font/opentype
    application/vnd.ms-fontobject
    image/svg+xml;
  gzip_static on;
  gzip_proxied        expired no-cache no-store private auth;
  gzip_disable        "MSIE [1-6]'.";
  gzip_vary           on;

重新启动NGINX

service nginx restart/etc/init.d/nginx restart

NGINX Gzip文档:http://nginx.org/en/docs/http/ngx_http_gzip_module.html