用于 AWS Amazon ELB 运行状况检查的 Nginx 解决方案 - 不带 IF 返回 200

Ada*_*dam 26 nginx amazon-ec2 amazon-web-services amazon-elb

我有以下代码在 Nginx 上工作,以保持 AWS ELB 健康检查。

map $http_user_agent $ignore {
  default 0;
  "ELB-HealthChecker/1.0" 1;
}

server {
  location / {
    if ($ignore) {
      access_log off;
      return 200;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我知道 Nginx 最好避免使用“IF”,我想问一下是否有人会知道如何在没有“if”的情况下重新编码?

谢谢你

cee*_*yoz 72

不要把事情复杂化。只需将您的 ELB 健康检查指向一个专门为他们服务的特殊 URL。

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


小智 31

只是为了改进上述答案,这是正确的。以下效果很好:

location /elb-status {
    access_log off;
    return 200 'A-OK!';
    # because default content-type is application/octet-stream,
    # browser will offer to "save the file"...
    # the next line allows you to see it in the browser so you can test 
    add_header Content-Type text/plain;
}
Run Code Online (Sandbox Code Playgroud)


Bab*_*abu 5

更新:如果需要用户代理验证,

set $block 1;

# Allow only the *.example.com hosts. 
if ($host ~* '^[a-z0-9]*\.example\.com$') {
   set $block 0;
}

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

if ($block = 1) { # block invalid requests
  return 444;
}

# Health check url
location /health {
  return 200 'OK';
  add_header Content-Type text/plain;
}
Run Code Online (Sandbox Code Playgroud)