Friday, June 22, 2018

Compression/Decompression in Nginx


Introduction
------------

- compression saves bandwidth but has extra cpu overhead
- by default, nginx compresses data before sending to client
- nginx doesn't double compress data (e.g response from a proxied server)
- to enable comression on proxied request, use `gzip_proxied`
- compression directives can be included in any of the ff contexts:
    a. http
    b. server
    c. location

Enabling Compression
--------------------

enables compression for
MIME type text/html
gzip on;

compresses data with
other MIME types
gzip_types text/plain application/xml;
gzip on;
specify minimum length
of response to compress
(default is 20 bytes)
gzip_min_length 1000;
enables compression on
proxied requests
gzip_proxied no-cache no-store private expired auth;
  # - compresses responses whose "Cache-Control" header field has
  #   any of the following:
  #    a. no-cache
  #    b. no-store
  #    c. private
  # - `expired` tells nginx to check the "Expires" field
  # - `auth` tells nginx to check the "Authorization" field
actual example
server {
    gzip on;
    gzip_types      text/plain application/xml;
    gzip_proxied    no-cache no-store private expired auth;
    gzip_min_length 1000;
    ...
}

Enabling Decompression
----------------------

- some clients doens't support responses with `gzip` encoding
- nginx can decompress response on the fly to accomodate such clients
- `gunzip` directive is used for decompression
    -> might not be included in Nginx opensource
    -> can be placed on same contexts as `gzip` directive

enables runtime decompression
location /storage/ {
    gunzip on;
    ...
}

Sending Compressed Files
------------------------

Sends a compressed version
of the file instead of the
regular one
location / {
  gzip_static on;
    # - a requested /file will be sent as /file.gz to client
    # - if file doesn't exist/cient doesn't support gzip,
    #   Nginx sends uncompressed version
    # - `gzip_static` doesn't enable on-the-fly compression;
    #   it simply sends the compressed file
    # - to compress content at runtime, use `gzip` directive
}

No comments:

Post a Comment