【问题标题】:How to enable gzip on a Nginx web server?如何在 Nginx Web 服务器上启用 gzip?
【发布时间】:2016-08-28 05:06:27
【问题描述】:

我尝试在我的网站上启用 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

【问题讨论】:

    标签: javascript .htaccess svg nginx gzip


    【解决方案1】:

    NGINX 不支持 .htaccess 文件。

    Like Apache: .htaccess

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

    为了在 NGINX 网络服务器上启用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多