0

I use Cloudflare for my domains.

I've noticed a situation in my access.log file that when someone attempts to connect directly (via the IP address) the $http_x_forwarded_for value is "-", which is correct and by design as $http_x_forwarded_for isn't being set by Cloudflare.

I want to do the following (see first if block), but nginx won't allow it in the main nginx.conf file. Is there another way to do this?

  if ($http_x_forwarded_for = '-') {
    $http_x_forwarded_for = $remote_addr;
  }

  # format: e.g., $http_cf_ipcountry derives from the Cloudflare header HTTP_CF_IPCOUNTRY;
  # the others too follow this format
  log_format complete '$remote_addr - $remote_user [$time_local] '
                      '"$request" $status $body_bytes_sent '
                      '"$http_referer" "$http_user_agent" "$host" '
                      '"$http_x_forwarded_for" "$http_cf_ipcountry" "$http_accept_language"';

1 Answer 1

1

Using maps instead of if / else :)

Add this to your http context block:

log_format complete '$remote_addr - $remote_user [$time_local] '
                      '"$request" $status $body_bytes_sent '
                      '"$http_referer" "$http_user_agent" "$host" '
                      '"$logforwarded" "$http_cf_ipcountry" "$http_accept_language"';


map $http_x_forwarded_for $logforwarded {
     default $http_x_forwarded_for;
     ''  $remote_addr;
 }

The access-log entry will look like this: ::1 - - [02/Mar/2020:05:51:46 -0500] "GET / HTTP/1.1" 200 4 "-" "curl/7.29.0" "localhost" "::1" "-" "-"

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Timo, great example!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.