NGINX:检查$ remote_user是否等于该位置的第一部分

时间:2014-10-28 10:45:45

标签: regex nginx elasticsearch

我无法弄清楚如何配置检查$remote_user是否等于location的第一部分。

location / {
  auth_basic "ElasticSearch";
  auth_basic_user_file /etc/nginx/search_passwords;

  location ~/([^/]*)/ { # named capture did not work either
    if ($remote_user = $1) { # ERROR: Unknown variable: $1 / $NAMEDWHATEVER
      break;
    }
  }
}

我的用例:

我正在努力"安全" ElasticSearch-Cluster通过使用nginx-reverse代理进行身份验证。我想允许多个用户,但新用户的修改应该尽可能简单;最好的情况 - 只需更改htpasswd文件。

我尝试采用nginx-elasticsearch-proxy但未检查remote_nameindex-name是否相等。

1 个答案:

答案 0 :(得分:3)

这应该是可能的,您还可以在与正则表达式匹配时定义变量的名称。

在下面的代码片段中,我将正则表达式的结果分配给变量 $ username 。然后我可以检查它,如果匹配 $ remote_user (确保正确设置了这个,以防我像我一样调试它)然后我在响应中添加了一个额外的标题,这样你就可以看到使用Firebug network console或仅使用curl命令。

看看这个是否有助于你。

location / {
  auth_basic "ElasticSearch";
  auth_basic_user_file /etc/nginx/search_passwords;

  location ~ /(?<username>([^/]*))/ { # capture and store in the username variable
    if ($remote_user = $username ) { 
      add_header 'matched' 'true $username'; 
      break;
    }
  }
}

有关详细信息,请参阅此How to I get variables from location in nginx?