Nginx 返回 200 而不提供文件

Kek*_*eke 3 http nginx http-status-code-404 nginx-location nginx-status

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

server {
  location = /hoge {
    return 200;
  }
}
Run Code Online (Sandbox Code Playgroud)

但curl命令失败。

curl localhost:80/hoge
Run Code Online (Sandbox Code Playgroud)

它说

<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>
Run Code Online (Sandbox Code Playgroud)

日志是

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"
Run Code Online (Sandbox Code Playgroud)

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

我改成这个但仍然不起作用。

location /hoge {
return 200 'Wow';
add_header Content-Type text/plain;
}
Run Code Online (Sandbox Code Playgroud)

也尝试过这个。

location /hoge {
return 200 'Wow';
default_type text/plain;
}
Run Code Online (Sandbox Code Playgroud)

Kom*_*omu 8

没有上下文(整个 nginx 配置文件的样子)很难说,因为nginx 处理请求的方式

像下面这样的配置文件应该可以很好地满足您的需求:

  server {
    listen 80;

    location /hoge {
      return 200;
    }

  }
Run Code Online (Sandbox Code Playgroud)

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

  server {
    listen 80;

    location /hoge {
      return 200;
    }

    location ~* /ho {
      return 418;
    }

  }
Run Code Online (Sandbox Code Playgroud)

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

所以,长答案是;如果没有您正在使用的整个 nginx conf 文件的上下文,很难判断。但了解nginx 如何处理请求会让你找到答案。