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.

2
  • 1
    Since 1.7.0 nginx's access_log has if parameter. See docs
    – Alexey Ten
    Apr 23, 2015 at 8:52
  • Why do that at all instead of just greping the log for bad referers?
    – AD7six
    Apr 23, 2015 at 8:53

3 Answers 3

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).

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;
    }

    ...
}
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;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .