monicahq/laravel-cloudflare
Laravel middleware that automatically trusts Cloudflare proxy IP ranges so client IPs and forwarded headers are handled correctly. Drop-in replacement for Laravel’s TrustProxies, with an optional callback to customize how proxy lists are loaded.
composer require monicahq/laravel-cloudflare
TrustProxies middleware in bootstrap/app.php:
->withMiddleware(function (Middleware $middleware) {
$middleware->replace(
\Illuminate\Http\Middleware\TrustProxies::class,
\Monicahq\Cloudflare\Http\Middleware\TrustProxies::class
);
})
php artisan cloudflare:reload
php artisan cloudflare:view to confirm the cached IPs.request()->ip() now returns the correct client IP (via CF-Connecting-IP header).Middleware Integration:
TrustProxies middleware, leveraging Cloudflare’s IP ranges to trust proxies dynamically..env or other middleware).Caching Strategy:
routes/console.php:
Schedule::command('cloudflare:reload')->daily();
Custom Proxy Logic:
AppServiceProvider::boot():
LaravelCloudflare::getProxiesUsing(fn() => customProxyLogic());
IP Replacement (Advanced):
replace_ip in config/laravelcloudflare.php to replace the request IP with CF-Connecting-IP:
'replace_ip' => true,
CF-Connecting-IP header to be present (Cloudflare’s default behavior)..env:
LARAVEL_CLOUDFLARE_ENABLED=false
CloudflareProxies for unit tests:
LaravelCloudflare::getProxiesUsing(fn() => ['1.1.1.1/32']);
php artisan vendor:publish --provider="Monicahq\Cloudflare\TrustedProxyServiceProvider") to customize cache TTL or proxy behavior per environment.Cache Staleness:
cloudflare:reload in staging/production.php artisan cloudflare:view to verify cached IPs match Cloudflare’s official list.Header Conflicts:
CF-Connecting-IP is missing, the middleware falls back to the original IP. Ensure Cloudflare is properly configured to forward this header.Middleware Order:
TrustProxies entirely. Mixing it with other proxy middleware (e.g., TrustProxies with custom proxies) may cause conflicts.Laravel Version Mismatches:
\Log::debug('Trusted Proxies:', config('trustedproxies.proxies'));
CF-Connecting-IP is present in requests:
\Log::debug('CF Headers:', request()->header());
Custom Proxy Sources:
CloudflareProxies to fetch IPs from an API or database:
class CustomCloudflareProxies extends \Monicahq\Cloudflare\CloudflareProxies {
public function load() {
return $this->fetchFromCustomSource();
}
}
AppServiceProvider:
LaravelCloudflare::getProxiesUsing(fn() => (new CustomCloudflareProxies())->load());
Dynamic TTL:
config/laravelcloudflare.php:
'cache_ttl' => 1440, // 1 hour (default: 86400 = 24h)
IP Whitelisting:
TrustProxies’s proxies config to merge Cloudflare IPs with static IPs:
TRUSTED_PROXIES=192.168.1.0/24,1.1.1.0/24
How can I help you explore Laravel packages today?