Linux – Nginx, log referrers from certain domain to separate log file

linuxlog-filesloggingnginx

I have my nginx setup to block certain referers like so:

if ($http_referer ~* (site_name) ) {
  return 403;
}

This works fine, however I'd like to also log the blocked referrer to a separate file.

I tried adding

 access_log /path/to/server/bad_domain.log;

in the if statement; however this doesn't work.

Any ideas?

Thanks.

Edit:

I've also tried this to no avail.

if ($http_referer ~* (site_name) ) {
  set $crawler 'yes';
  return 403;


}

location ~ .* {
  if ($crawler = 'yes') {
  access_log /path/to/server/bad_domain.log;
    }
}

Edit 2:

Trying

map $http_referer $log_referer {
  domain1.com  1;
  default      0;
}

server { ..
    if ($http_referer = "1") {
    set $log_referer 1;
}
   access_log /path/to/logs/bad_domain.log if=$log_referer;

...}

Gives me the output of

nginx: [emerg] unknown log format "if=$log_referer"

Best Answer

According to nginx documentation found here and here, try to use map rule to map your http referer to certain value and then log to specific file according that value. Put this map in your http context (outside the server context):

map $http_referer $log_referer {
  example.com  1;
  default      0;
}

This goes to your server, location, etc.;

access_log /path/to/bad_domain.log combined if=$log_referer;