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:
- Edit your nginx configuration file (
/etc/nginx/nginx.conf
or a site-specific configuration file) as a user with sufficient privileges. - Locate the section that defines the
http
block and add thegzip
directive to it. - 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. - Specify the types of files to compress using the
gzip_types
directive. By default, nginx compresses onlytext/html
files, but you can add more MIME types as needed. - 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.