[英]Laravel Request returning load balancer ip instead of client ip
當我嘗試獲取客戶端 ip 地址時遇到問題
request()->ip()
它返回給我私人服務器 IP 而不是客戶端 IP。
如何避免這種情況可能是什么原因。
問這個問題的原因是我的支付網關需要一個公共 IP 來接受付款
實際上,我在這里找到了一個適用於 Laravel 官方文檔中編寫的所有環境的解決方案。
有一個稱為可信代理App\Http\Middleware\TrustProxies
的中間件。
該中間件負責解析代理,它有一個名為proxies
的屬性。
我只是將proxies
屬性設置為私有 IP 的數組,它就起作用了。
這是修改后的樣子。
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array|string
*/
protected $proxies = [
'x.x.x.x',
];
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
不要忘記將xxxx
替換為您的私有 IP。
現在當我調用以下 function
request()->ip();
它給了我預期的結果。
您可以使用
request()->header('X-Forwarded-For')
並檢查您的負載均衡器的配置方式,也許您忘記了 Original IP 和 X-Forwarded-For 標頭
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.