nginx: Disable logging for certain request(s)

As long as configured in a server directive, nginx logs every request in a logfile. Whenever you want to exclude (a) certain request(s), e. g. with dynamical parameters, from getting logged, it’s not that easy. For this reason I want to show a possible solution which works on nginx since version 1.7.0. The used map feature is not included in older nginx versions.

At first you have to declare the request you don’t want to get logged. In my case it was the following: /board/index.php?page=ChatMessageBot&id=X. The X was a dynamic number. If you have unwanted requests of just a directory or a single file, it is very easy to disable logging for them by using the following code inside a server directive:

location /do-not-log.txt { access_log off; }

On a dynamical request or a request with parameters it’s not that easy so you need the mapfeature. In my case it looks like the following and is specified outside the server directive:

map $request_uri $loggable { ~/board/index\.php\?page=ChatMessageBot* 0; default 1; }

Declaration: I map the $request_uri to the variable $loggable. If the request from above is sent to the server, the variable $loggable gets a value of 0, otherwise it gets a value of 1. Of course you can set multiple requests, each per line, with a value of 0 so that they doesn’t get saved in the logfile too.
The ~ at the beginning of line 2 marks the following characters as regular expressions. In this case it is necessary for me to match my dynamic request.

After this you have to expand the line inside your server directive where the access log is declared to check for the variable $loggable:
access_log /var/log/nginx/access.log combined if=$loggable;
The extension if=$loggable indicates that there will be something written into the log only if $loggable returns the value true, at which 0 is false and 1 is true.

The last thing to do is to reload the nginx configuration, e. g. via sudo service nginx reload. Now there shouldn’t be any requests logged, which match the declared request URI.

2 thoughts on “nginx: Disable logging for certain request(s)

  1. Thanks for this info – it solved a ‘healthcheck spam’ problem for me.

    ‘access_log off;’ doesn’t support the ‘if’ argument, so I ended up sending the spammy logs to /dev/null instead:

    access_log /dev/null combined if=$donotlog;

    1. Correction – I spoke too soon. It doesn’t really work this way, with the ‘do not log’ workflow. If your access log doesn’t satisfy the ‘if’, then it doesn’t get logged at all… so you end up with a condition where you will lose the log regardless of what the value is.

      I flipped it to the $loggable format you described and it works. My mistake.

      Thanks again!

Leave a Reply to vacri Cancel reply

Your email address will not be published. Required fields are marked *