如何避免使用 nginx 配置进行 AWS ELB 运行状况检查的基本身份验证

Sam*_*_TT 6 passenger nginx amazon-web-services amazon-elb

我在尝试为 ELB 运行状况检查实施基本身份验证时遇到了麻烦。我已经搜索了很多以找出 nginx 文件配置以避免如下所示的 401 错误,这是由于基本身份验证而导致 ELB 返回的

unhealthy in target-group hogehoge due to (reason Health checks failed with these codes: [401])

我试图修改 nginx.conf 以避免它,但它不起作用。下面的代码给了我[emerg] "server" directive is not allowed here错误。

http {
    server {
        location / {
            if (!$http_x_forwarded_for) {
                auth_basic           'Please enter ID and password';
                auth_basic_user_file /usr/src/redmine/.htpasswd;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

由于基本身份验证,如何避免 ELB 运行状况检查出现 401 错误?

谢谢您的帮助。

nba*_*ari 11

最简单的方法是为 ELB 创建一个位置,例如:

location /elb-status {
  access_log off;
  return 200;
}
Run Code Online (Sandbox Code Playgroud)

您只需要更改Ping Path/elb-status

如果您想在测试时在浏览器上看到某些内容,您可能需要将content-type默认值更改为,application/octet-stream并且浏览器将提供保存文件的功能,因此应该可以使用以下内容:

location /elb-status {
   access_log off;
   return 200 'your text goes here';
   add_header Content-Type text/plain;
}
Run Code Online (Sandbox Code Playgroud)

如果你想检查用户代理,可以使用这样的东西:

set $block 1;

# Allow all the ELB health check agents.
if ($http_user_agent ~* '^ELB-HealthChecker\/.*$') {
    set $block 0;
}
if (!$http_x_forwarded_for) {
    set $block 1
}

if ($block = 1) {
    auth_basic           'Please enter ID and password';
    auth_basic_user_file /usr/src/redmine/.htpasswd;
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然 if 就像@CyrilDuchon-Doris 提到的那样是邪恶的(因为它们是 Nginx 声明式风格中的命令式构造),但它们在服务器块内使用是非常安全的......请参阅 [Nginx on ifs] (https://www.nginx.com /resources/wiki/start/topics/depth/ifisevil/),特别是他们说的地方: > “要做什么,请使用 try_files 如果它适合您的需要。使用“return ...”或“rewrite ... last ”在其他情况下。在某些情况下,也可以将 ifs 移动到服务器级别(这是安全的,因为其中只允许其他重写模块指令)。” (2认同)