Ever thought of enabling gzip compression on nginx web server for JS/CSS/HTML files?
Here is how:
You need to use the ngx_http_gzip_module module.
It compresses all valid HTTP responses (files) using the “gzip” method.
This is useful to reduce data transfer size and speed up web pages for static assets such as JavaScript, CSS files and more.
Steps to enable gzip/deflate in nginx server
Edit your nginx.conf file or create a new config file called /etc/nginx/conf.d/static_gzip.conf:
$ sudo vi /etc/nginx/nginx.conf
Add the following in http context:
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
Save and close the file. Verify that there are no errors in config file:
$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Restart the nginx server
Type the following command to restart or reload nginx server:
$ sudo service nginx reload
OR
$ sudo systemctl reload nginx
OR
$ sudo /etc/init.d/nginx reload
How do I verify if gzip/deflate is working?
Use the following syntax:
$ curl -I -H 'Accept-Encoding: gzip,deflate' https://your-domain-here/file.css
$ curl -I -H 'Accept-Encoding: gzip,deflate' https://s0.cyberciti.org/assets/auto/cms/wp-content/cache/autoptimize/css/autoptimize_4c2bea242e2386438912dd88773b352c.css
$ curl -I -H 'Accept-Encoding: gzip,deflate' https://www.cyberciti.biz/
Sample outputs:
HTTP/1.1 200 OK
Server: nginx
Date: Sun, 05 Mar 2017 18:45:31 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Vary: Accept-Encoding
X-Whom: l1-com-cyber
Strict-Transport-Security: max-age=15768000; includeSubdomains
Link: ; rel="https://api.w.org/"
X-Varnish: 1812270 1794298
Age: 475
Via: 1.1 varnish-v4
Front-End-Https: on
Content-Encoding: gzip
That should be it!