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.

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

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

| improve this answer | |

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;

| improve this answer | |

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;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.