1

Map variables to $clientIP with regex.

Webserver behind multiple CDN, The custom header with the client's real ip varies. So I came out with the follow expression.

#here I use @ as seperator
map "$http_cf_connecting_ip@$http_cdn_src_ip@$http_src_ip@$http_client_ip" $clientIP {

          "~[^-]+@-@-@-$"       $http_cf_connecting_ip;                 
          "~^-@[^-]+@-@-$"      $http_cdn_src_ip;        
          "~^-@-@[^-]+@-$"      $http_src_ip;             
          "~^-@-@-@[^-]+$"      $http_client_ip;
          "~^-@-@-@-$"          $remote_addr;
          default               $remote_addr;
}

I use postman to send custom http headers. But seems map will always go to default.

0

1 Answer 1

1

The empty variables are probably just empty, rather than containing a literal hyphen. The access log uses a hyphen to indicate empty values.

You could rewrite your regular expressions to match the empty variables, or just use a named capture to match the first place containing a valid IP address.

For example:

map "$http_cf_connecting_ip@$http_cdn_src_ip@$http_src_ip@$http_client_ip" $clientIP {
    ~(^|@)(?<ipaddr>\d+\.\d+\.\d+\.\d+)($|@)    $ipaddr;
    default                                     $remote_addr;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Totally right "The empty variables are probably just empty, rather than containing a literal hyphen",I am debugging the variables in access_log,thank you.

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.