Venederis
Venederis

Reputation: 1067

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?

Upvotes: 10

Views: 24115

Answers (2)

foibs
foibs

Reputation: 3406

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.

Upvotes: 3

VBart
VBart

Reputation: 15130

error_page 404 =200 @empty_json;

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

Reference:

Upvotes: 20

Related Questions