Add Cloudflare ip addresses to trusted proxies for Laravel.
- Install package using composer:
composer require monicahq/laravel-cloudflare
You don't need to add this package to your service providers.
- Configure Middleware
- Option 1: Add Cloudflare TrustProxies middleware and remove default one
Replace TrustProxies
middleware in app/Http/Kernel.php
, by modifying the middleware
array:
protected $middleware = [
- \App\Http\Middleware\TrustProxies::class,
+ \Monicahq\Cloudflare\Http\Middleware\TrustProxies::class
...
- Option 2: Extend current middleware to use Cloudflare TrustProxies middleware
Another option is to extend the App\Http\Middleware\TrustProxies
class to Monicahq\Cloudflare\Http\Middleware\TrustProxies
:
namespace App\Http\Middleware;
use Illuminate\Http\Request;
- use Illuminate\Http\Middleware\TrustProxies as Middleware;
+ use Monicahq\Cloudflare\Http\Middleware\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
...
You can define your own proxies callback by calling the LaravelCloudflare::getProxiesUsing()
to change the behavior of the LaravelCloudflare::getProxies()
method.
This method should typically be called in the boot
method of your AppServiceProvider
class:
use Monicahq\Cloudflare\LaravelCloudflare;
use Monicahq\Cloudflare\Facades\CloudflareProxies;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
LaravelCloudflare::getProxiesUsing(function() {
return CloudflareProxies::load();
});
}
The middleware uses Illuminate\Http\Middleware\TrustProxies as a backend.
When the cloudflare ips are detected, they are used as trusted proxies.
This package retrieves Cloudflare's IP blocks, and stores them in cache. When request comes, the middleware will get Cloudflare's IP blocks from cache, and load them as trusted proxies.
You'll need to refresh the cloudflare cache regularely to always have up to date proxy.
Use the cloudflare:reload
artisan command to refresh the IP blocks:
php artisan cloudflare:reload
Add a new line in app/Console/Kernel.php
, in the schedule
function:
$schedule->command('cloudflare:reload')->daily();
You can use the cloudflare:view
artisan command to see the cached IP blocks:
php artisan cloudflare:view
If you want, you can publish the package config file to config/laravelcloudflare.php
:
php artisan vendor:publish --provider="Monicahq\Cloudflare\TrustedProxyServiceProvider"
This file contains some configurations, but you may not need to change them normally.
Laravel | monicahq/laravel-cloudflare |
---|---|
5.x-6.x | <= 1.8.0 |
7.x-8.53 | 2.0.0 |
8.54-9.x | >= 3.0.0 |
This package was inspired by lukasz-adamski/laravel-cloudflare and forked from ogunkarakus/laravel-cloudflare.
Author: Alexis Saettler
This project is part of MonicaHQ.
Copyright © 2019–2022.
Licensed under the MIT License. View license.