1

Because someone steals content from our website, I need to create additional log file, that logs only if http_referrer contains specific domain.

Currently I have this:

   if ($http_referer ~* (bad-domain.com)){
           return  500;
   }

But instead of return 500, i need to return normal response, but to log the request.

Nick
  • 786
  • 2
  • 12
  • 37

3 Answers3

3

The access_log directive is valid inside if, so you can simply add one there.

However, its presence overrides any ones that appear above it in the hierarchy, so if you simply add one entry the request will not be logged to whatever access log you normally log for that server.

To get around that, you can use two access_log directives inside the if, one which repeats the regular access log, and one for your special access log (which can also use a different log_format if you wish).

Michael Hampton
  • 237,123
  • 42
  • 477
  • 940
1

Just putting access_log inside if, does not work

However access_log only inside if inside location and from this thread we can see the workaround:

Separate Nginx access log file for certain requests only

if ($http_referer ~* (bad-domain.com)){
  set $bad_domain 'yes';
}

location / {
  if ($bad_domain = 'yes') {
    access_log logs/bad_domain.log;
    return 200;
    }

    ...
}
Nick
  • 786
  • 2
  • 12
  • 37
0

Use map directive like this

map $http_referer $loggable_referer {
    default           0;
    ~*bad-domain.com  1;
}
access_log /var/log/nginx/bad_domain.log combined if=$loggable_referer;
DidThis
  • 111
  • 1