Skip to content

Instantly share code, notes, and snippets.

@Ingramz
Last active November 3, 2020 05:59
Show Gist options
  • Save Ingramz/bbb8f4f2634e0701c186 to your computer and use it in GitHub Desktop.
Save Ingramz/bbb8f4f2634e0701c186 to your computer and use it in GitHub Desktop.
Laravel 5 CloudFlare Proxy Middleware Compatibility
<?php
// ...
protected $middleware = [
// ...
'App\Http\Middleware\CloudFlareProxies',
];
// ...
<?php namespace App\Http\Middleware;
use Closure;
class CloudFlareProxies {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Proxies obtained from https://www.cloudflare.com/ips-v4
$request->setTrustedProxies([
'199.27.128.0/21',
'173.245.48.0/20',
'103.21.244.0/22',
'103.22.200.0/22',
'103.31.4.0/22',
'141.101.64.0/18',
'108.162.192.0/18',
'190.93.240.0/20',
'188.114.96.0/20',
'197.234.240.0/22',
'198.41.128.0/17',
'162.158.0.0/15',
'104.16.0.0/12'
]);
return $next($request);
}
}
@antriver
Copy link

Try this for automatic updates:

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $proxyIps = Cache::remember('cloudFlareProxyIps', 1440, function () {
            $url = 'https://www.cloudflare.com/ips-v4';
            $ips = file_get_contents($url);
            return array_filter(explode("\n", $ips));
        });

        $request->setTrustedProxies($proxyIps);

        return $next($request);
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment