简体   繁体   中英

How to enable gzip on a Nginx web server?

I tried to enable gzip on my website but with not good results. Checking with http://checkgzipcompression.com/ gzip shows enabled but when I go to https://gtmetrix.com/ to test my website's performance and speed it seems that gzip is not enabled for some files (eg. JavaScript files and SVG files).

What am I doing wrong?

In order to enable gzip I used an .htaccess and pasted the following code:

<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>

Before mod_deflate.c I also tried the following code too:

<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 Information

server  nginx
vary    Accept-Encoding

NGINX does not have support for .htaccess files.

Like Apache: .htaccess

You can't do this. You shouldn't. If you need .htaccess, you're probably doing it wrong.

In order to enable Gzip compression on your NGINX web server, first open your NGINX's default configuration file: sudo vim /etc/nginx/nginx.conf , and replace the existing Gzip settings with the following:

nginx.conf (you can modify the settings below according to your needs)

  # 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;

Restart NGINX

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM