How to Safely Enable Gzip on a HTTPS Site with NGINX

Ok, before you think "OH, YOU JUST DO gzip on AND IT WILL WORK!!! THIS IS CLICKBAIT!!!!!!" and click off. I just want to make you aware that enabling Gzip without any sort of protection will leave your HTTPS site vulnerable to BREACH attacks. In this post, I am going to show you how to safely enable Gzip on a HTTPS site.

One of the mitigations of BREACH involves adding a random length string in the responses. NGINX module ngx_http_length_hiding_filter_module does just that. Implementing in your configuration isn't hard. Here are the steps you can take to enable this module on NGINX in a Debian/Ubuntu environment.

  1. Install ngx_http_length_hiding_filter_module
    • Checkout NGINX source code
      $ apt source nginx
    • Install required packages
      # apt install libpcre3 libpcre3-dev
    • Checkout ngx_http_length_hiding_filter_module source code
      $ git clone https://github.com/nulab/nginx-length-hiding-filter-module.git
    • Configure NGINX with ngx_http_length_hiding_filter_module as a dynamic module
      $ cd nginx-1.18.0/
      $ ./configure --add-dynamic-module=../nginx-length-hiding-filter-module --with-compat
    • Build the module
      $ make modules
    • Copy the module to the modules directory
      # cp objs/ngx_http_length_hiding_filter_module.so /usr/lib/nginx/modules/
    • Create /etc/nginx/modules-available/mod-http-length-hiding-filter-module.conf, the file should include the following line
      load_module modules/ngx_http_length_hiding_filter_module.so;
  2. Enable the module
    # ln -s /etc/nginx/modules-available/mod-http-length-hiding-filter-module.conf /etc/nginx/modules-enabled/50-mod-http-length-hiding-filter-module.conf
  3. Edit the configuration file to reflect the changes
    server {
     ...
     length_hiding_max 1024;
     gzip on;
     gzip_vary on;
     gzip_proxied any;
     gzip_comp_level 6;
     gzip_buffers 16 8k;
     gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
     ...
     location / {
      ...
      length_hiding on;
      ...
     }
    ...
    }
  4. Restart NGINX
    # systemctl restart nginx

Now you should have your HTTPS site configured with Gzip securely. To test if the module is working, visit your website and press Ctrl + U. You should see a randomly generated string at the bottom as shown.