使用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());
記錄一下 以免忘記