【问题标题】:Return 200 by Nginx without serving a fileNginx 返回 200 而不提供文件
【发布时间】:2018-08-04 19:08:35
【问题描述】:

我写了这个/etc/nginx/conf.d/apply.conf 并启动了 nginx。

server {
location = /hoge {
    return 200;
}

}

但是 curl 命令失败了。

curl localhost:80/hoge

上面写着

<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.13.9</center>
</body>
</html>

日志是

open() "/usr/share/nginx/html/hoge" failed (2: No such file or directory), client: 127.0.0.1, server: localhost, request: "GET /hoge HTTP/1.1", host: "localhost"

我只想返回没有响应正文或响应正文空白的状态代码。

我改成这个还是不行。

location /hoge {
return 200 'Wow';
add_header Content-Type text/plain;
}

也试过这个。

location /hoge {
return 200 'Wow';
default_type text/plain;
}

【问题讨论】:

  • location 块很好,但您将其放入错误的 server 块中。请参阅how nginx processes a request 了解更多信息。
  • 谢谢。我找到了它不工作的原因,这就是你所说的。
  • @KeKe 能否请您发布原因是什么,这会有所帮助。我遇到了同样的问题,尝试了您发布的所有内容以及更多内容,但仍然无法弄清楚问题所在。

标签: http nginx http-status-code-404 nginx-location nginx-status


【解决方案1】:

很难说没有上下文(你的整个 nginx 配置文件看起来如何),因为how nginx processes a request

如下所示的配置文件应该可以很好地满足您的需求:

  server {
    listen 80;

    location /hoge {
      return 200;
    }

  }

但是,如果您的配置文件有其他位置块(特别是如果它们是基于正则表达式的),那么您可能无法获得预期的解决方案。 以这个配置文件为例:

  server {
    listen 80;

    location /hoge {
      return 200;
    }

    location ~* /ho {
      return 418;
    }

  }

curl localhost:80/hoge 发送请求将返回http 状态代码418 而不是200。这是因为正则表达式位置在确切位置之前匹配。

所以,长答案是;如果没有您正在使用的整个 nginx conf 文件的上下文,很难判断。但是了解how nginx processes a request 会让你得到答案。

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 2021-01-30
    • 1970-01-01
    • 2018-10-23
    • 2019-07-17
    • 2018-06-28
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多