Last active
March 9, 2023 14:26
-
-
Save tillkruss/d5fd36d23afd9ddebbb4 to your computer and use it in GitHub Desktop.
Running Laravel 5 on Heroku behind CloudFlare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Kernel extends HttpKernel | |
{ | |
protected $middleware = [ | |
\App\Http\Middleware\TrustedProxies::class, | |
]; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
@ghprod of course, why wouldn't it?
@tillkruss would this work for Heroku without Cloudflare?
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
Is it working with throttle middleware?