Nginx stub_status: Ignore own requests

2019-03-06 02:47发布

问题:

When enabling the stub_status in Nginx, statistics about the server can be queried:

location /stats {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

I'm interested in the "requests handled" metric. The problem is that this metric includes the requests sent to query the current status.

Is there a way to ignore the requests against /stats in the reported data?

回答1:

As you can see in the source code, the counter is incremented exactly at the moment when a new request "object" is being created. That is, even before any request header, including the URI, is parsed. So the answer is no, unfortunately there is no way to tell Nginx not to count requests for a particular URI.

However, there are two ways to solve the problem. Unfortunately, both of them involve building your own copy of Nginx:

  1. You could patch the stub status module Nginx directly, decrementing request conter every time the stub_status directive generates the output. To do this you only need to include this line at the end of this function.

  2. The other more proper way is to introduce your own module that would do exactly the same. Here is a quickly made example of such a module. Somewhat surprising, but you don't need strong knowledge of C to create simple modules, as Nginx offers its own framework for that and also there are hundreds of examples available on GitHub.