Nginx enable gzip
Asked Answered
B

1

17

I want enable the gzip compression on my nginx server. The nginx.conf file is here:

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" { }

  }
}   

Unfortunately the gzip compression not working, Google Pagespeed and Gtmetrix not detect this.

Where can I place the gzip conf?

In The http{} server{} or location{} tag?

I already tried in the http and in the location tags too

Bruni answered 29/9, 2016 at 16:41 Comment(0)
O
34

You can put the gzip configuration anywhere, but if you want to apply it to all websites / files it is best to put it in the http section - this will then be the default for all server and location blocks. I would also "shorten" / change your config to the following:

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
}

I use that configuration and it works fine for me - you can also test it in your browser first (for example with Firebug) before testing it with external services.

Using gzip_static only makes sense if you actually generate gzipped files for Nginx (as filename + .gz), so this has nothing to do with enabling gzip and should only be a possible second step.

Ossie answered 30/9, 2016 at 1:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.