0%

Ignore 404 not found logs in Nginx

I recently used Nginx to serve a few static JSON files as lightweight configuration endpoints. The simplest configuration looks like this:

1
2
3
location ~ ^/myconf/(?<filename>.*)$ {
alias /home/knktc/myconf/$filename;
}

The problem is that when the requested file does not exist, Nginx returns its default 404 page. To make this easier for frontend code to handle, I changed the configuration so that missing files return an empty JSON object instead:

1
2
3
4
5
6
7
8
9
location ~ ^/myconf/(?<filename>.*)$ {
alias /home/knktc/myconf/$filename;
error_page 404 = @not_found_fallback;
}

location @not_found_fallback {
add_header Content-Type text/plain;
return 200 "{}";
}

Now, if the file is missing, the response is an empty JSON object.

But there is still another issue: Nginx will log the 404 event in error.log even though the client gets the fallback response.

So the configuration needs one more change to suppress the not-found log:

1
2
3
4
5
6
7
8
9
10
location ~ ^/myconf/(?<filename>.*)$ {
alias /home/knktc/myconf/$filename;
error_page 404 = @not_found_fallback;
log_not_found off;
}

location @not_found_fallback {
add_header Content-Type text/plain;
return 200 "{}";
}

That does the trick. Using Nginx’s static file handling for simple lightweight interfaces can be quite convenient.

如果我的文字帮到了您,那么可不可以请我喝罐可乐?