Nginx反向代理 Laravel獲取真實IP地址(PHP)
阿新 • • 發佈:2018-11-27
代理 pro $1 通過 找到 但是 有一個 忘記 rust
使用VUE前後端分離開發
後端使用Laravel 想要獲取到用戶的真實IP地址
因為分離開發不同源跨域問題 所以只能進行前端Nginx反向代理
location /api { rewrite ^/api/(.*)$ /api/$1 break; proxy_pass https://***.********.com; }
然後在後端獲取IP地址的時候 通過原始方法
$request->getClientIp();
發現返回的只是代理服務器的IP地址
查找資料獲得方法
在前端Nginx代理配置寫入
location /api { rewrite^/api/(.*)$ /api/$1 break; proxy_pass https://***.*********.com; } proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
插入之後進行Nginx重啟發現warning錯誤
Starting nginx: nginx: [warn] could not build optimal proxy_headers_hash, you should increase either proxy_headers_hash_max_size: 512 or proxy_headers_hash_bucket_size: 64; ignoring proxy_headers_hash_bucket_size
然後進行查找資料 解決辦法
在nginx.conf配置文件裏面的http代碼塊裏面加入
http{ ... proxy_headers_hash_max_size 51200; proxy_headers_hash_bucket_size 6400;
之後重啟就沒有報錯信息了
但是使用
$request->getClientIp();
還是代理服務器IP地址
找到方法發現獲取的是
REMOTE_ADDR
隨後打印$_SERVER
發現真是的IP地址存在於
$_SERVER[‘HTTP_X_FORWARDED_FOR‘]
幸好我只有一處使用了這個IP 暫時用這個代替了
還有一個辦法就是在
$request->getClientIp();
之前加入
$request->setTrustedProxies($request->getClientIps()); //這個可以放入到中間件中 這樣就不用更改代碼了 var_dump($request->getClientIp());
記錄一下 以免忘記
Nginx反向代理 Laravel獲取真實IP地址(PHP)