由于某种原因,位置指令似乎不起作用

Location directive doesn't seem to be working for some reason

几天前,我在 k8s 部署中偶然发现了 Nginx。由于我对 Nginx 比较陌生,所以我想了解它是如何工作的 - 所以我进行了自己的开发部署。

问题是我的 nginx.conf 无法按预期工作:

  1. 当您访问 /healthz 端点时,return 200(k8s 健康检查)
  2. 将任何其他 http 流量重定向到 https

这是我当前的nginx.conf

server {
  listen 80;
  listen [::]:80;
  server_name _;

  location /healthz {
    return 200 "healthy";
  }
  return 301 https://$host$request_uri;

  access_log off;
  error_log /usr/share/nginx/web/logs/http_error.log error;
}

server {
  listen 443 ssl http2 default_server;
  listen [::]:443 ssl http2 default_server;
  server_name company.com;

  root /usr/share/nginx/web;
  index index.html;

  access_log off;
  error_log /usr/share/nginx/web/logs/ssl_error.log error;

  ssl_certificate /usr/share/nginx/web/cert/company.crt;
  ssl_certificate_key /usr/share/nginx/web/cert/company.key;
}

我得到的响应(我已经删除了 IP 地址):

[error] 28#28: *2 open() "/usr/share/nginx/web/healthz" failed (2: No such file or directory), client: xx.xx.xx.xx, server: company.com, request: "GET /healthz HTTP/2.0", host: "xx.xx.xx.xx", referrer: "http://xx.xx.xx.xx:80/healthz"

Request is on port 80 to /healthz but instead of returning 200, it gets redirected to the https server where it fails

此时我真的不知道为什么它不起作用,所以请,即使是一些愚蠢的错误,请随时指出!
我在这里做错了什么?

ngx_http_rewrite_moduleserver 上下文(包括 return 一个)处理的所有指令在来自 location 上下文的相同指令之前执行。您应该定义两个位置以实现所需的行为:

server {
    listen 80;
    listen [::]:80;
    server_name _;

    access_log off;
    error_log /usr/share/nginx/web/logs/http_error.log error;

    location / {
        return 301 https://$host$request_uri;
    }
    location /healthz {
        return 200 "healthy";
    }
}