【问题标题】:Location directive doesn't seem to be working for some reason由于某种原因,位置指令似乎不起作用
【发布时间】:2020-11-07 18:32:18
【问题描述】:

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

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

  1. 访问/healthz端点时,返回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"

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

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

【问题讨论】:

    标签: nginx webserver nginx-location


    【解决方案1】:

    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";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多