Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MKraynikov's avatar

Authorization for direct file links

Hello.

It's necessary to protect direct links to files in Laravel.

In config/filesystems.php created new disk:

'files' => [
            'driver' => 'local',
            'root' => storage_path('app/files'),
            'url' => env('APP_URL').'/files',
            'visibility' => 'public',
            'throw' => false,
        ]

Created route in web.php:

Route::get('files/{file}', FilesController::class)->middleware(['auth']);

And FilesController:

public function __invoke($file)
    {
        abort_if(
            ! Storage::disk('files') ->exists($file),
            404,
            "The file doesn't exist. Check the path."
        );

        return Storage::disk('files')->response($file);
    }

When going to the address in an unauthorized session, the file is downloaded and displayed:

localhost:8000/files/yR2LJHkS2lYTd4RlUFbfkRCzaktZiP0EH3w9AVMp.jpg

To check i changed the route to this one:

Route::get('/files/yR2LJHkS2lYTd4RlUFbfkRCzaktZiP0EH3w9AVMp.jpg', function (Request $request) {
    Log::info('Get file URL test.');  
});

But nothing happened, the test message was not written to the log.

How to intercept a file request in a route and process it in a controller to check user authorization?

Project run on Docker with sail-8.3/app

0 likes
4 replies
krisi_gjika's avatar

can you also post your webserver config? it may be miss configured to serve static files from non public/* directories

MKraynikov's avatar

@krisi_gjika Project run on Docker with sail-8.3/app as far as I know he doesn't use apache or nginx as webserver. If this is not the case, please tell me where I can find this configuration?

Snapey's avatar
Snapey
Best Answer
Level 122

make sure you dont have a symlink for files in your document root

1 like
MKraynikov's avatar

@Snapey Thank you for your reply. Now it works correctly. Yes, indeed I added in config/filesystems.php rows:

'links' => [
        public_path('storage') => storage_path('app/public'),
        public_path('files') => storage_path('app/files'),
    ],

When unlink symlink to "files" it worked correctly.

Thanks again to everyone for their help.

Please or to participate in this conversation.