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;
}Code language: Nginx (nginx)

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;
}Code language: Nginx (nginx)

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.

Leave a Reply

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