How to reply with 200 from Nginx, without serving a file?
I have configured Apache to send back a 200 response without serving any file with this configuration line
Redirect 200 /hello
Can I do this with Nginx? I don't want to serve a file, I just want the server to respond with a 200 (I'm just logging the request).
I know I can add an index file and achieve the same thing, but doing it in the config means there's one less thing that can go wrong.
Solution 1:
Yes, you can
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;
}
Solution 2:
You do need to use a 204 as Nginx will not allow a 200 with no response body. To send a 204 you simply use the return directive to return 204;
in the appropriate location.
Solution 3:
If you want to return a formatted HTML text, without serving a HTML file:
location / {
default_type text/html;
return 200 "<!DOCTYPE html><h2>gangnam style!</h2>\n";
}
If you want to return a text without html format, as the answer points:
location / {
add_header Content-Type text/plain;
return 200 'gangnam style!';
}
And if you just simply wants to return 200:
location / {
return 200;
}
Just to remember: location
blocks go inside server
blocks. Here's a doc for more info.
P.S.: I have similar configuration (formatted html) runnning on plenty of servers.
Solution 4:
To complete @Martin Fjordval's answer, be careful if you're using such a configuration to do a healthcheck.
While a 204
HTTP code is semantically perfect for a healthcheck (success indication with no content), some services do not consider it a success.
Namely, I had the issue with Google Cloud Load-balancers.
Solution 5:
As per status code definitions, I believe you want it to be a 204, and not 200. 200's need to be with a resource in the response, or I'd suspect most sane browsers would get confused by this. The other one you can use is 304, which is for cached content.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html