0
0
NginxHow-ToBeginner · 3 min read

How to Set gzip_types in Nginx for Compression

To set gzip_types in Nginx, add the directive inside the http or server block with a list of MIME types you want to compress, like gzip_types text/plain application/json;. This tells Nginx which content types to compress using gzip, improving load times for those resources.
📐

Syntax

The gzip_types directive specifies which MIME types Nginx should compress using gzip. It is used inside the http, server, or location blocks.

Each MIME type is separated by a space. Common types include text/plain, text/css, application/json, and application/javascript.

nginx
gzip_types mime-type [mime-type ...];
💻

Example

This example shows how to enable gzip compression for common text-based MIME types inside the http block of the Nginx configuration.

nginx
http {
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    server {
        listen 80;
        server_name example.com;

        location / {
            root /var/www/html;
            index index.html;
        }
    }
}
Output
Nginx will compress responses with the specified MIME types when gzip is enabled and the client supports it.
⚠️

Common Pitfalls

  • Forgetting to enable gzip: The gzip on; directive must be set, or gzip_types has no effect.
  • Not including the correct MIME types: If a MIME type is missing, that content won't be compressed.
  • Over-compressing binary files: Avoid compressing already compressed files like images or videos, as it wastes CPU.
  • Placing gzip_types outside allowed blocks: It must be inside http, server, or location blocks.
nginx
## Wrong: gzip_types outside http/server/location blocks
# gzip_types text/plain;

## Right:
http {
    gzip on;
    gzip_types text/plain;
}
📊

Quick Reference

DirectiveDescriptionExample
gzip on;Enables gzip compression globally or per blockgzip on;
gzip_typesSpecifies MIME types to compressgzip_types text/plain application/json;
gzip_min_lengthMinimum response size to compressgzip_min_length 1000;
gzip_disableDisables gzip for specific user agentsgzip_disable "msie6";

Key Takeaways

Always enable gzip with gzip on; before setting gzip_types.
gzip_types lists MIME types that Nginx will compress with gzip.
Place gzip_types inside http, server, or location blocks.
Avoid compressing binary files like images to save CPU resources.
Common MIME types to compress include text, JSON, CSS, JavaScript, and XML.