The problem: when try to retrieve client’s ip in Laravel with $request->ip(
); it always return the reverse proxy IP address.
In order to retrieve the client’s real IP the frontend server has to forward the client’s IP into the backend server.
NGINX front end configuration:
location /api {
proxy_pass http://10.0.23.80; // your api backend server address
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header HTTP_X_FORWARDED_FOR $remote_addr;
proxy_redirect default;
}
NGINX back end configuration
server {
# ...
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
}
Apache back end configuration
<VirtualHost _default_:443>
# ...
RemoteIPHeader X-Forwarded-For
</VirtualHost>
Once the configuration is in place, client’s real ip should be forwarded to the backend server.
Laravel get client’s IP
request()->setTrustedProxies(request()->getClientIps,\Illuminate\Http\Request::HEADER_X_FORWARDED_FOR);
echo request()->ip();