Serve files from a private Cloudflare R2 bucket through your Laravel application.
This package proxies whitelisted paths from a private R2 bucket, allowing you to serve certain files publicly while keeping everything else secure. No need to make your bucket public or configure complex access policies—just define which path prefixes should be accessible and the package handles the rest with configurable caching headers.
composer require aarondfrancis/r2proxyPublish the config file:
php artisan vendor:publish --tag=r2proxy-configIf you don't already have an R2 disk configured, follow the Laravel S3 driver documentation to set one up.
Once you have an R2 disk, change the driver from s3 to r2_public:
// config/filesystems.php
'r2' => [
// Change from 's3' to 'r2_public'
'driver' => 'r2_public',
// The route prefix for proxied files (e.g. /r2/images/photo.jpg)
'url' => '/r2/',
// ... rest of your existing R2 config
],Then configure which disks should be proxied in config/r2proxy.php:
use AaronFrancis\R2Proxy\PathValidator;
return [
'disks' => [
'r2' => [
'path_validator' => PathValidator::directories('images', 'videos'),
],
],
];You can proxy multiple disks, each with their own path validator and cache settings:
'disks' => [
'r2' => [
'path_validator' => PathValidator::directories('images', 'videos'),
],
'r2-assets' => [
'path_validator' => PathValidator::matches('css/*', 'js/*'),
'cache' => [
'max_age' => 86400, // 1 day
],
],
],The temporaryUrl method returns a proxy URL for public paths:
// Returns /r2/images/photo.jpg (proxied through your app)
$url = Storage::disk('r2')->temporaryUrl('images/photo.jpg', now()->addHour());
// Private paths still get signed S3 URLs
$url = Storage::disk('r2')->temporaryUrl('private/secret.pdf', now()->addHour());use AaronFrancis\R2Proxy\Filesystem\R2PublicAdapter;
if (R2PublicAdapter::isPathAllowed('images/photo.jpg', 'r2')) {
// Path is publicly accessible on the 'r2' disk
}Directories - allow entire directories:
use AaronFrancis\R2Proxy\PathValidator;
'path_validator' => PathValidator::directories('images', 'uploads'),Patterns - wildcard matching with *:
'path_validator' => PathValidator::matches('images/*.jpg', 'videos/*.mp4'),Only paths allowed by the path validator are accessible through the proxy. Requests to other paths return a 403 Forbidden response. Directory traversal attacks are blocked regardless of validator configuration.
- Files in public paths are served through
/{url-prefix}/{path}routes - The controller streams files directly from R2 with proper headers
- Cache-Control headers are added for browser/CDN caching
- Private files still use signed S3 URLs via the parent adapter
MIT