nginx: Disable logging for certain request(s)

Warning: This page is a part of an archive now and will be removed in the future.

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:

Source Code

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

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

Source Code

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

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.
About the Author
Ich bin Webentwickler in Stuttgart und administriere Server seit vielen Jahren. In diesem Blog erstelle ich hauptsächlich Tutorials für andere Webentwickler, Webdesigner und Serveradministratoren.
-------------------------------------------------------------------------------------------------------------------------------------
I’m a web developer in Stuttgart, Germany, and server administrator since many years. This blog mainly contains a tutorial set for other web developer, web designer and server administrators.

3,928 times read

Comments 0

There are not any items at the moment.

This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.