Search code examples
nginxhttp-refererbreach-attack

Nginx: Selectively enable compression based on referrer hostname


In order to mitigate against the BREACH attack, I would like to selectively enable gzip only when $http_referer's hostname matches one of my server names.

How would I do this? I tried using valid_referers server_names;, but it seems like nginx doesn't allow gzip on inside if statements. When I include this in my conf:

valid_referers server_names;

if ($invalid_referer = "") {
    gzip on;
    gzip_vary on;
}

I get [emerg] "gzip" directive is not allowed here. The must be a way to selectively enable gzip.


Solution

  • The nginx documentation specifies that the gzip option is allowed in the following contexts

    Context: http, server, location, if in location

    This means you need to wrap the gzip switch inside a location block.

    gzip  off;
    
    server {
      listen 80; 
      server_name localhost;
      valid_referers server_names;
    
      location / { 
        root /var/www/;
        index index.html index.htm;
    
        if ($invalid_referer = "") {
           gzip on; 
        }
      }
    }