How to set up gzip compression in nginx?

Published on Aug. 22, 2023, 12:19 p.m.

To set up gzip compression in nginx, you need to add the gzip directive to your nginx configuration file. This tells nginx to compress the responses before sending them to the clients.

Here are the general steps:

  1. Edit your nginx configuration file (/etc/nginx/nginx.conf or a site-specific configuration file) as a user with sufficient privileges.
  2. Locate the section that defines the http block and add the gzip directive to it.
  3. Specify the compression level (from 1 to 9) using the gzip_comp_level directive. By default, nginx uses a compression level of 1, which is a good balance between compression ratio and CPU usage.
  4. Specify the types of files to compress using the gzip_types directive. By default, nginx compresses only text/html files, but you can add more MIME types as needed.
  5. Save the changes to the configuration file and reload nginx service to apply the changes.

Here’s an example of what the http block might look like with gzip compression enabled:

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

Note that you may also want to set the gzip_min_length directive to specify the minimum size of files to compress, and the gzip_proxied directive to determine when to compress responses for reverse proxy requests.

After you’ve made changes to the nginx configuration file, you need to reload the nginx service to apply the changes.

Tags: