Skip to content

Instantly share code, notes, and snippets.

@tillkruss
Last active March 9, 2023 14:26
Show Gist options
  • Select an option

  • Save tillkruss/d5fd36d23afd9ddebbb4 to your computer and use it in GitHub Desktop.

Select an option

Save tillkruss/d5fd36d23afd9ddebbb4 to your computer and use it in GitHub Desktop.
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

Copy link
Copy Markdown
Author

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.

@fer-ri

fer-ri commented Sep 7, 2017

Copy link
Copy Markdown

Is it working with throttle middleware?

@tillkruss

Copy link
Copy Markdown
Author

@ghprod of course, why wouldn't it?

@brickgale

brickgale commented Oct 24, 2017

Copy link
Copy Markdown

@tillkruss would this work for Heroku without Cloudflare?

@tillkruss

Copy link
Copy Markdown
Author

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