HAProxy 搭配 CodeIgniter 取使用者真實 IP

前端 Load Balance 首選就是 HAProxy,後端架設 Nginx 搭配 CodeIgniter,紀錄使用者 IP 時,Nginx 總是只有抓到內部 IP 192.168.x.x,而無法抓到真實 Public IP,要抓到 Public IP 必須修改 HAProxy + Nginx 設定檔,HAProxy 只要在 Backend 地方加入 forward 選項,這樣 HAProxy 會送 X-Forwarded-For header 給後端 Nginx。

option forwardfor

接著設定 Nginx 部份,必須編譯

ngx_http_realip_module 模組,在 nginx.conf 加入

set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;
這樣就可以拿到真實 IP 了,最後在 CodeIgniter 找到 config.php 設定檔
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy IP
| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR
| header in order to properly identify the visitor's IP address.
| Comma-delimited, e.g. '10.0.1.200,10.0.1.201'
|
*/
$config['proxy_ips'] = '192.168.1.100,192.168.1.101,192.168.1.102';
將 proxy_ips 設定好即可

See also