Nginx:根据引用主机名有选择地启用压缩

Nginx: Selectively enable compression based on referrer hostname

为了减轻 BREACH 攻击,我想仅在 $http_referer 的主机名与我的服务器名称之一匹配时有选择地启用 gzip。

我该怎么做?我尝试使用 valid_referers server_names;,但似乎 nginx 不允许在 if 语句中使用 gzip on。当我将其包含在我的 conf 中时:

valid_referers server_names;

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

我得到 [emerg] "gzip" directive is not allowed here。必须是一种有选择地启用 gzip 的方法。

nginx documentation 指定在以下上下文中允许使用 gzip 选项

Context: http, server, location, if in location

这意味着您需要将 gzip 开关包装在 location 块中。

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; 
    }
  }
}