Disable logging in nginx for specific request

2019-02-09 09:00发布

问题:

I'm trying to "ignore" or redirect certain request in the nginx log based on the request URI.

So far I have this:

server {
  listen      80;
  #...
  access_log  /var/log/nginx/site.access;
  error_log   /var/log/nginx/site.error info;
  #...

  try_files $uri @app

  location = /lbcheck.html {
    access_log off;
    log_not_found off;
    try_files $uri @app;
  }

  location @app {
    proxy_redirect     off;
    proxy_pass http://unix:/tmp/site.unicorn.sock;
    #...
  }

}

Basically I want the proxied @app to respond to the request for /lbcheck.html but I don't want it logged in /var/log/nginx/site.access;

I know i can do it with a if ($uri = /lbcheck.html) { access_log off; } in location @app but if's are evil, so I don't want to use them.

回答1:

You can do this with conditional logging. It would look something like

map $request $loggable {
    ~*lbcheck\.html 0;
    default 1;
}
access_log  /path/logs/name.log if=$loggable;


回答2:

I'm not sure if there is a way of doing it just within Nginx's configuration syntax, I just tried and it didn't seem possible without an if statement.

However I do know that doing it in the way you're trying to is against Nginx's philosophy of how to write config files.

Instead of writing complicated config rules, you should be generating your nginx.conf files with whatever configuration tool you prefer, so that the actual config file is simple, with all the complicated bits generated for you by your tool.

e.g. your source file that your nginx.conf is generated from should look something like:

%START_APP_CONFIG%
    proxy_redirect     off;
    proxy_pass http://unix:/tmp/site.unicorn.sock;
%END_APP_CONFIG%


location = /lbcheck.html {
    access_log off;
    %INSERT_APP_CONFIG%
}

location @app {
    %INSERT_APP_CONFIG%
}

Although this may seem like a lot of work to just be able to tweak a single config variable, it actually makes using config files much more pleasant in the long (and medium) term as you will always be generating config files that are easy to read and understand, rather than having complicated conditions in them.



标签: logging nginx