如何从 Nginx 回复 200,而不提供文件?

The*_*heo 196 http nginx html

我已将 Apache 配置为发回 200 响应,而不使用此配置行提供任何文件

Redirect 200 /hello
Run Code Online (Sandbox Code Playgroud)

我可以用 Nginx 做到这一点吗?我不想提供文件,我只希望服务器响应 200(我只是记录请求)。

我知道我可以添加一个索引文件并实现相同的目的,但是在配置中执行此操作意味着可能会出错的事情少了一件。

cad*_*dmi 393

是的你可以

location / {
    return 200 'gangnam style!';
    # because default content-type is application/octet-stream,
    # browser will offer to "save the file"...
    # if you want to see reply in browser, uncomment next line 
    # add_header Content-Type text/plain;
}
Run Code Online (Sandbox Code Playgroud)

  • add_header 对我不起作用,因为它添加了另一个标题而不是替换旧的“内容类型”。在我的回复中,我有 2 个“内容类型”标头:$ curl -v localhost/healthcheck/h1_pio > GET /healthcheck/h1_pio HTTP/1.1 > User-Agent: curl/7.38.0 > Host: localhost > Accept: */ * > < HTTP/1.1 200 OK < 日期:2016 年 10 月 11 日星期二 13:27:53 GMT < Content-Type: application/octet-stream < Content-Length: 25 < Connection: keep-alive < Content-Type: application /json (7认同)
  • @jmcollin92 如果您在其他地方声明了现有的 default_type,则可能会发生这种情况。您可以通过在 location 块内使用 `default_type text/plain;` 代替 `add_header` 指令来覆盖它。 (7认同)
  • @tback 当然,你是对的 (3认同)
  • 提示:如果您没有返回“成功”代码,请使用 `add_header Content-Type text/plain always;` 强制使用纯文本。 (3认同)
  • 如何在响应中添加换行符?`江南\nstyle`? (2认同)
  • @jmcollin92 您的评论与提出的问题和给出的答案无关。因为你显然有某种proxy_pass,fascgi_pass,等等......但我仍然回答 location /healthcheck/h1_pio { # proxy_pass blablabla what you need; proxy_hide_header 内容类型;add_header 内容类型应用程序/json;将来,在适当的位置正确地提出您的问题 (2认同)

Mar*_*ald 29

您确实需要使用 204,因为 Nginx 不允许使用没有响应正文的 200。要发送 204,您只需在适当的位置使用return 指令即可return 204;


iva*_*ncz 18

如果要返回格式化的 HTML 文本,而不提供 HTML 文件:

location / {
    default_type text/html;
    return 200 "<!DOCTYPE html><h2>gangnam style!</h2>\n";
}
Run Code Online (Sandbox Code Playgroud)

如果你想返回一个没有 html 格式的文本,作为答案:

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

如果你只是想返回 200:

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

请记住:location块在server块内。这是一个文档以获取更多信息。

PS:我有类似的配置(格式化的 html)在很多服务器上运行。


小智 7

要完成@Martin Fjordval 的回答,如果您使用此类配置进行健康检查,请务必小心。

虽然204HTTP 代码在语义上非常适合健康检查(没有内容的成功指示),但某些服务并不认为它是成功的。

也就是说,我遇到了Google Cloud Load-balancers 的问题


san*_*oid 6

根据状态代码定义,我相信您希望它是 204,而不是 200。200 需要在响应中包含资源,否则我怀疑大多数理智的浏览器都会对此感到困惑。您可以使用的另一个是 304,用于缓存内容。

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

  • 一个空的 body 仍然是一个响应,带有一个对象,比如一个空白的 index.html。您要求的是提供一个没有附加资源的 200 响应(没有提供文件)。至于在nginx上具体怎么做,我需要自己查一下,我只在apache上做过一次,一时想不起来了。 (2认同)