Gzip compression in Nginx reduces the number of bytes sent for text responses, improving page load time and lowering bandwidth usage for websites and APIs.
Nginx applies gzip when the client advertises Accept-Encoding: gzip and the response is eligible based on content type and size. When compression is applied, Nginx signals it with Content-Encoding: gzip and cache correctness is preserved by returning Vary: Accept-Encoding.
Compression trades CPU for bandwidth, so aggressive settings can reduce throughput on busy servers. Limit compression to text-like MIME types, avoid already-compressed formats (JPEG/PNG/ZIP, etc.), and validate behavior under representative load—especially when a CDN or reverse proxy may already be compressing responses.
Steps to enable gzip compression in Nginx:
- Add gzip directives inside the http block of /etc/nginx/nginx.conf (or an included file loaded from that block).
http { gzip on; gzip_comp_level 5; gzip_min_length 256; gzip_vary on; gzip_proxied any; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/rss+xml application/atom+xml image/svg+xml; ##### snipped ##### }text/html is compressed by default; gzip_types adds additional MIME types.
- Test the Nginx configuration for syntax errors.
$ sudo nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
- Reload Nginx to apply the configuration changes.
$ sudo systemctl reload nginx
On systems without systemd, reload with sudo nginx -s reload.
- Confirm gzip is active by checking for Content-Encoding: gzip when requesting with Accept-Encoding: gzip.
$ curl -I -H 'Accept-Encoding: gzip' http://127.0.0.1/ | grep -iE '^(content-encoding|vary):' Content-Encoding: gzip Vary: Accept-Encoding
If no Content-Encoding header appears, check that the response Content-Type matches gzip_types and that the body exceeds gzip_min_length.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.
Comment anonymously. Login not required.
