Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Running Laravel 5 on Heroku behind CloudFlare
<?php
class Kernel extends HttpKernel
{
protected $middleware = [
\App\Http\Middleware\TrustedProxies::class,
];
}
<?php
namespace App\Http\Middleware;
use Closure;
use ReflectionClass;
use Symfony\Component\HttpFoundation\{IpUtils, Request};
class TrustedProxies
{
const CLOUDFLARE = [
'103.21.244.0/22',
'103.22.200.0/22',
'103.31.4.0/22',
'104.16.0.0/12',
'108.162.192.0/18',
'131.0.72.0/22',
'141.101.64.0/18',
'162.158.0.0/15',
'172.64.0.0/13',
'173.245.48.0/20',
'188.114.96.0/20',
'190.93.240.0/20',
'197.234.240.0/22',
'198.41.128.0/17',
'199.27.128.0/21',
'2400:cb00::/32',
'2405:8100::/32',
'2405:b500::/32',
'2606:4700::/32',
'2803:f800::/32',
'2c0f:f248::/32',
'2a06:98c0::/29',
];
public function handle($request, Closure $next)
{
$request->setTrustedProxies(self::CLOUDFLARE);
// These are not set by AWS or Heroku
$request->setTrustedHeaderName(Request::HEADER_FORWARDED, null);
$request->setTrustedHeaderName(Request::HEADER_CLIENT_HOST, null);
if ($request->server->has('HTTP_CF_CONNECTING_IP')) {
$proxies = preg_split('~\s?,\s?~', $request->server->get('HTTP_X_FORWARDED_FOR'));
// Do we trust every proxy, aside from the client IP address?
$trustProxies = collect($proxies)
->splice(1)
->every(function ($ip) {
return IpUtils::checkIp($ip, self::CLOUDFLARE);
});
// Replace Heroku router IP address with a Cloudflare IP address
if ($trustProxies) {
$request->server->set('REMOTE_ADDR', $proxies[1]);
}
}
return $next($request);
}
}
@tillkruss

This comment has been minimized.

Copy link
Owner Author

@tillkruss tillkruss commented Apr 3, 2017

On Heroku REMOTE_ADDR is always the private IP address of the last router. Laravel/Symfony tests REMOTE_ADDR against the "trusted proxies" to determine if the X_FORWARDED_FOR/HOST/PROTO/PORT is trustworthy.

@ghprod

This comment has been minimized.

Copy link

@ghprod ghprod commented Sep 7, 2017

Is it working with throttle middleware?

@tillkruss

This comment has been minimized.

Copy link
Owner Author

@tillkruss tillkruss commented Sep 7, 2017

@ghprod of course, why wouldn't it?

@brickgale

This comment has been minimized.

Copy link

@brickgale brickgale commented Oct 24, 2017

@tillkruss would this work for Heroku without Cloudflare?

@tillkruss

This comment has been minimized.

Copy link
Owner Author

@tillkruss tillkruss commented Oct 24, 2017

No, Heroku doesn't have fixed IP ranges, they use AWS.

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