Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

antriver commented Nov 19, 2015

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