首页 > 解决方案 > 由于某种原因,位置指令似乎不起作用

问题描述

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

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

  1. 访问/healthz端点时,返回200(k8s 的健康检查)
  2. 将任何其他流量重定向httphttps

这是我目前的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"

请求在端口80上,/healthz但不是返回200,而是重定向到https失败的服务器

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

标签: nginxwebservernginx-location

解决方案


ngx_http_rewrite_module上下文中处理的所有指令server(包括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";
    }
}

推荐阅读