Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx return an empty json object with fake 200 status code

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?

like image 329
Deltanic Avatar asked Nov 12 '13 13:11

Deltanic


2 Answers

error_page 404 =200 @empty_json;

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

Reference:

  • http://nginx.org/r/error_page
  • http://nginx.org/r/return
  • http://nginx.org/r/location
like image 159
VBart Avatar answered Oct 12 '22 10:10

VBart


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.

like image 39
foibs Avatar answered Oct 12 '22 10:10

foibs