> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Compression

> Explains using gzip and Brotli in NGINX to compress text assets, compare algorithms, configure settings, and avoid compressing already compressed media.

Think of packing a suitcase for a week in Hawaii. If you stuff clothes without folding them, they take more space and are harder to close. Fold them neatly and you fit more. Compression does the same for data: it reduces the size of files sent over the network so they consume less bandwidth and arrive faster.

When an HTTP server compresses a response, it sends a smaller encoded version to the browser. The browser then decompresses and renders the original content. Without compression, the server sends full HTML, JavaScript, CSS, and other assets — increasing load times and data usage for end users, especially on mobile or metered connections.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/5f0mE-FaFIAKk82W/images/Nginx-For-Beginners/Performance/Compression/compression-recycling-compactor-worker-conveyor.jpg?fit=max&auto=format&n=5f0mE-FaFIAKk82W&q=85&s=7b212b15df0bf6e23a690bfcfad7752e" alt="An illustration labeled &#x22;Compression&#x22; showing a sanitation worker wheeling a recycling bin and carrying a trash bag. To the right, a conveyor belt feeds recyclables into a large compactor/machine marked with a recycling symbol." width="1920" height="1080" data-path="images/Nginx-For-Beginners/Performance/Compression/compression-recycling-compactor-worker-conveyor.jpg" />
</Frame>

The end result of proper compression: less data transferred, faster page loads, and a better user experience.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/5f0mE-FaFIAKk82W/images/Nginx-For-Beginners/Performance/Compression/fast-response-useful-data-server-browser.jpg?fit=max&auto=format&n=5f0mE-FaFIAKk82W&q=85&s=05eefdb5a2b357c82452307e1606b0dc" alt="An infographic titled &#x22;Fast Response&#x22; showing a server on the left sending only useful data (icons and an arrow) to a browser displayed on a laptop on the right. The components are labeled &#x22;Server&#x22; and &#x22;Browser.&#x22;" width="1920" height="1080" data-path="images/Nginx-For-Beginners/Performance/Compression/fast-response-useful-data-server-browser.jpg" />
</Frame>

## What resources should you compress?

Text-based resources usually compress well and should be enabled for compression:

* HTML, CSS, JavaScript
* JSON, XML
* RSS, SVG, text files
* Font files (e.g., `font/woff`, `font/woff2`) — can be included selectively

Binary media and many archive formats are already compressed; recompressing them yields little benefit and wastes CPU:

* JPEG, PNG (use modern formats like WebP or AVIF instead for better compression)
* MP4, MP3, AVI, ZIP, TAR

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/5f0mE-FaFIAKk82W/images/Nginx-For-Beginners/Performance/Compression/supported-compression-file-icons.jpg?fit=max&auto=format&n=5f0mE-FaFIAKk82W&q=85&s=38d77eaf17179f48788b6827c99555f4" alt="A slide titled &#x22;Supported Compression&#x22; showing a rounded-square graphic of six file icons labeled CSS, HTML, XML, JSON, JS and JPEG, with a green checkmark indicating support." width="1920" height="1080" data-path="images/Nginx-For-Beginners/Performance/Compression/supported-compression-file-icons.jpg" />
</Frame>

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/5f0mE-FaFIAKk82W/images/Nginx-For-Beginners/Performance/Compression/unsupported-compression-avi-mp4-mp3-zip.jpg?fit=max&auto=format&n=5f0mE-FaFIAKk82W&q=85&s=8e91993ecefcf41e0dadf62faae9a115" alt="A slide titled &#x22;Unsupported Compression&#x22; showing four file icons (AVI, MP4, MP3, ZIP) inside a rounded box. A red X next to the box indicates those formats are not supported." width="1920" height="1080" data-path="images/Nginx-For-Beginners/Performance/Compression/unsupported-compression-avi-mp4-mp3-zip.jpg" />
</Frame>

Table — quick guidance

| Should compress                                                                          | Should generally not compress                                   |
| ---------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| `text/html`, `text/css`, `application/javascript`, `application/json`, `application/xml` | `video/mp4`, `audio/mpeg`, `application/zip`                    |
| `text/plain`, `application/rss+xml`, `image/svg+xml`                                     | Already compressed images (JPEG/PNG) — prefer WebP/AVIF instead |

## Supported algorithms in NGINX

NGINX supports two widely used compression algorithms: gzip and Brotli.

### gzip

* Widely supported across browsers and servers (legacy compatibility).
* Compression levels 1–9 (1 = fastest, 9 = best compression, default commonly 6).
* Available as a built-in NGINX feature on most distributions.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/5f0mE-FaFIAKk82W/images/Nginx-For-Beginners/Performance/Compression/gzip-facts-slide-compression-default-6.jpg?fit=max&auto=format&n=5f0mE-FaFIAKk82W&q=85&s=82fd580acaf53d1bf535196ae836cf0a" alt="A slide about Gzip showing an icon and brief facts (released in the 90s, .gz file format, available on Linux/Unix, use the gzip CLI). It also shows a compression-level scale from 1 to 9 with 6 marked as the default." width="1920" height="1080" data-path="images/Nginx-For-Beginners/Performance/Compression/gzip-facts-slide-compression-default-6.jpg" />
</Frame>

Example: compress a file using the gzip CLI

```bash theme={null}
$ gzip ubuntu-jammy-jellyfish.iso
$ ls -l
-rw-r--r-- 1 user user  10G Jun 20 12:00 ubuntu-jammy-jellyfish.iso.gz
```

Recommended minimal nginx.conf gzip configuration (place inside the `http { ... }` block, often in `/etc/nginx/nginx.conf`):

```nginx theme={null}
http {
    gzip on;
    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
        text/html
        text/xml
        text/javascript
        application/json
        application/javascript
        application/rss+xml;
}
```

Notes:

* `gzip on;` — enable gzip compression.
* `gzip_comp_level` — set CPU vs. compression trade-off (1–9). Level 6 is a sensible default.
* `gzip_types` — list MIME types to compress (add `font/woff` and `font/woff2` if desired).
* `gzip_proxied any;` — allows compression for proxied requests.

### Brotli

* Better compression ratios in many cases (levels 0–11).
* Modern browsers advertise Brotli via `br` in `Accept-Encoding`.
* Not always built into stock NGINX; often provided via the third-party ngx\_brotli module or available in vendor packages.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/5f0mE-FaFIAKk82W/images/Nginx-For-Beginners/Performance/Compression/brotli-nginx-plus-debian-ubuntu-slide.jpg?fit=max&auto=format&n=5f0mE-FaFIAKk82W&q=85&s=96340c9cfbd70ba66c96044a32a9d4f5" alt="A presentation slide titled &#x22;Brotli - Nginx Plus&#x22; showing the Brotli logo with the words &#x22;brotli&#x22; and &#x22;Debian/Ubuntu&#x22; beside it. The slide also has a small &#x22;© Copyright KodeKloud&#x22; note in the corner." width="1920" height="1080" data-path="images/Nginx-For-Beginners/Performance/Compression/brotli-nginx-plus-debian-ubuntu-slide.jpg" />
</Frame>

Brotli is commonly added to open-source NGINX via the ngx\_brotli module. See the module repository for installation options and instructions:

* ngx\_brotli: [https://github.com/google/ngx\_brotli](https://github.com/google/ngx_brotli)

Comparison (gzip vs Brotli)

| Feature               | gzip      | Brotli                          |
| --------------------- | --------- | ------------------------------- |
| Browser support       | Universal | Modern browsers (`br`)          |
| Compression levels    | 1–9       | 0–11                            |
| Typical ratio         | Good      | Often better than gzip          |
| CPU cost              | Moderate  | Can be higher at top levels     |
| Availability in NGINX | Built-in  | Requires module or vendor build |

If you decide to build NGINX from source to include third-party modules (e.g., Brotli), the typical sequence is:

```bash theme={null}
# download nginx source
wget https://nginx.org/download/nginx-1.27.0.tar.gz
tar zxf nginx-1.27.0.tar.gz
cd nginx-1.27.0

# configure with desired options and modules (example)
./configure \
  --sbin-path=/usr/local/nginx/nginx \
  --conf-path=/usr/local/nginx/nginx.conf \
  --pid-path=/usr/local/nginx/nginx.pid \
  --with-pcre=../pcre2-10.42 \
  --with-zlib=../zlib-1.2.13 \
  --with-http_ssl_module \
  --with-stream \
  --with-mail=dynamic \
  --add-module=/usr/build/nginx-rtmp-module \
  --add-dynamic-module=/usr/build/3party_module

# then
make && sudo make install
```

Compiling NGINX adds complexity and is usually unnecessary unless you require a specific third-party module not available from your vendor.

## How the server and browser negotiate compression

Clients tell servers which encodings they accept via the `Accept-Encoding` request header. Example request header from a browser:

```http theme={null}
Request Headers
:method: GET
:path: /main.bundle.js
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
pragma: no-cache
```

If the server chooses gzip or Brotli, it responds with a `Content-Encoding` response header indicating the encoding used. Example response headers:

```text theme={null}
Response Headers
content-encoding: gzip
content-type: text/html; charset=UTF-8
date: Fri, 27 May 2016 16:53:50 GMT
server: gws
status: 200
```

To confirm compression is active:

1. Open your browser DevTools → Network tab.
2. Select a resource and inspect Response Headers for `Content-Encoding`.
3. Confirm the resource is smaller than the uncompressed version (DevTools shows transfer size vs resource size).

<Callout icon="lightbulb" color="#1CB2FE">
  Avoid compressing already-compressed formats (MP4, MP3, ZIP, most JPEGs). Compress text-based assets (HTML, CSS, JS, JSON, XML) to get the best savings with minimal CPU overhead.
</Callout>

## Summary and recommendations

* Enable gzip by default for broad compatibility; start with `gzip_comp_level 6`.
* Use Brotli if you can add/enable the module and want better compression ratios for text assets — balance the Brotli level against CPU cost.
* Do not compress already-compressed media and archive formats; instead adopt modern image formats (WebP/AVIF) where appropriate.
* Verify using browser DevTools (check `Accept-Encoding` and `Content-Encoding` headers).

If you want to try this hands-on, enable gzip in your NGINX configuration, reload NGINX, and use browser DevTools to verify `Content-Encoding` behavior for HTML, CSS, and JS resources.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/nginx-for-beginners/module/4a5db5c4-df5f-4291-84f0-013d1c4ce235/lesson/f9e0c6ca-f04d-4d94-8b23-b342c8161065" />
</CardGroup>
