Nginx启用gzip

17

我想在我的nginx服务器上启用gzip压缩。nginx.conf文件在这里:

http {
  # Enable Gzip
  server {

    location ~* \.(?:ico|woff|css|js|gif|jpe?g|png)$ {
        expires 30d;
        add_header Pragma public;
        add_header Cache-Control "public";
    }

    location /api {
        try_files $uri $uri/ /api/index.php;
    }

    location / { ##merge
        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;

        try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" { add_header "" ""; }
    location ~ "^/ngx_pagespeed_static/" { }
    location ~ "^/ngx_pagespeed_beacon" { }

  }
}   

很遗憾,gzip压缩未生效,Google Pagespeed和Gtmetrix未检测到。

我应该把gzip配置放在哪里?

是在http{} server{}标签中还是location{}标签中?

我已经尝试过在httplocation标签中设置了。

1个回答

34

您可以将gzip配置放置在任何位置,但如果您希望将其应用于所有网站/文件,则最好将其放置在http部分 - 这将是所有服务器和位置块的默认设置。我还建议您将配置“缩短”/更改为以下内容:

http {
  gzip on;
  gzip_min_length  500;
  gzip_proxied     any;
  gzip_comp_level 4;
  gzip_types  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_vary on;
  gzip_disable     "msie6";

  ... here come your server blocks / rest of your config
}

我使用这个配置,它对我来说很有效 - 你也可以在测试外部服务之前先在浏览器中测试它(例如使用Firebug)。

只有在实际为Nginx生成gzip文件(文件名+ .gz)时,使用gzip_static才有意义,因此这与启用gzip没有任何关系,应该是可能的第二步。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接