Nginx return an empty json object with fake 200 status code

17,619

Solution 1

error_page 404 =200 @empty_json;

location @empty_json {
     return 200 "{}";
}

Reference:

Solution 2

You can always create a file in your document root called e.g. empty.json which only contains an empty object {}

Then in your nginx configuration add this line in your location block

try_files $uri /empty.json;

( read more about try_files )

This will check if the file requested by the client exists and if it does not exist it just shows empty.json instead. This produces a 200 HTTP OK and shows a {} to the requesting client.

Share:
17,619
Deltanic
Author by

Deltanic

Updated on July 23, 2022

Comments

  • Deltanic
    Deltanic almost 2 years

    We've got an API running on Nginx, supposed to return JSON objects. This server has a lot of load so we did a lot of performance improvements.

    The API recieves an ID from the client. The server has a bunch of files representing these IDs. So if the ID is found as a file, the contents of that file (Which is JSON) will be returned by the backend. If the file does not exists, no backend is called, Nginx simple sends a 404 for that, so we save performance (No backend system has to run).

    Now we stumbled upon a problem. Due to old systems we still have to support, we cannot hand out a 404 page for clients as this will cause problems. What I came up with, is to return an empty JSON string instead ({}) with a 'fake' 200 status code. This needs to be a highly performant solution to still be able to handle all the load.

    Is this possible to do, and if so, how?

  • lobengula3rd
    lobengula3rd about 9 years
    how can i return the specific response i got from a proxy server? if i used a module auth_subrequest
  • jmcollin92
    jmcollin92 over 7 years
    In your example the Content-Type header is set to application/octet-stream. I cannot figure out how to change the Content-Type. add_header add another Content-Type instead of replacing it
  • VBart
    VBart over 7 years
    @jmcollin92 Check the documentation: nginx.org/en/docs/http/ngx_http_core_module.html#default_typ‌​e It seems you have set this directive to application/octet-stream somewhere in your configuration.
  • jmcollin92
    jmcollin92 over 7 years
    No I haven't. I found a solution with this line : more_set_headers -t 'application/octet-stream' 'Content-Type: application/json'; It requires to add nginx-extras package (apt-get install nginx-extras)
  • VBart
    VBart over 7 years
    @jmcollin92 You should set the default_type directive. That's it. You don't need any extras.