我在尝试让 Larvel TrustedProxy 与 CloudFlare 和 AWS 的 EC2 弹性负载均衡器一起工作时遇到了困难。它假设您只使用 1 个代理,而不是 2 个并且不能正常工作。我最终只是跳过了所有受信任的代理内容并制作了一个简单的中间件,如果使用 CloudFlare,无论您前面是否有另一个负载均衡器,它都会设置正确的 IP 地址和协议。
CloudFlare 通过 HTTP 标头传递有关客户端的信息:https: //support.cloudflare.com/hc/en-us/articles/200170986-How-does-CloudFlare-handle-HTTP-Request-headers-
我们同时采用客户端 IP 和客户端 HTTP/HTTPS 协议并将其设置到 $request->server 属性中。
======
app/Http/Middleware/UseCloudFlareHeaders.php
<?php namespace App\Http\Middleware;
use Closure;
class UseCloudFlareHeaders
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//if CloudFlare request, set correct protocol and proper client ip address
$HTTP_CF_VISITOR = $request->server->get('HTTP_CF_VISITOR');
$HTTP_CF_CONNECTING_IP = $request->server->get('HTTP_CF_CONNECTING_IP');
if ($HTTP_CF_VISITOR and json_decode($HTTP_CF_VISITOR)->scheme == 'https') {
$request->server->set('HTTPS', 'on');
}
if ($HTTP_CF_CONNECTING_IP) {
$request->server->set('REMOTE_ADDR', $HTTP_CF_CONNECTING_IP);
}
return $next($request);
}
}
应用程序/Http/Kernal.php
protected $middleware = [
//add this to your middleware...
\App\Http\Middleware\UseCloudFlareHeaders::class
];
如果有人知道这样做的更好方法,请告诉我们。