Reputation: 2006
Ip have request flows through 3 nginx proxy, and ip got the x-forwarded-for list ip of :
192.168.10.222, 192.168.10.178, 192.168.10.179
how can I get the first ip using map module ? I've found this but can't make it working:
map $proxy_add_x_forwarded_for $client_ip {
"~(?<IP>([0-9]{1,3}\.){3}[0-9]{1,3}),.*" $IP;
}
from here: https://webkul.com/blog/x-forwarded-for-header-in-nginx-containing-mulitple-client-ips
Thanks
Upvotes: 1
Views: 3957
Reputation: 2006
find a more clear way:
map $http_x_forwarded_for $real_ip {
~^(\d+\.\d+\.\d+\.\d+) $1;
default $remote_addr;
}
Then we can use the new variable $real_ip
in geo
command:
geo $real_ip $backend {
default upstream-default;
1.1.1.1 upstream-backend001;
2.2.2.2 upstream-backend002;
}
or overwrite default log-format (replace $remote_addr
with $real_ip
):
#log_format main '$remote_addr - $remote_user [$time_local] '
log_format main '$real_ip - $remote_user [$time_local] '
'"$request" $http_host $status $request_length $body_bytes_sent '
'"$http_referer" "$uri" "$args" "$request_time" "$upstream_addr" '
'"$upstream_response_time" "$http_user_agent"';
Upvotes: 1
Reputation: 514
Thats what you are looking for:
map $proxy_add_x_forwarded_for $client_ip {"~(?<IP>([0-9]{1,3}\.){3}[0-9]{1,3}),.*" $IP;}
It will map the first ip of the 3 to the variable $client_ip. As one line out of the server and location scope.
Upvotes: 2