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

zorkwarrior's avatar

How to get response code from redirecting to a CDN for file download

I'm fairly new to Laravel.

I am creating a fall-back for application file downloads that I host locally and on my cloud git repo. I want to try the CDN, then get from local storage if it's down or not found.

I am using

redirect()->away($externalUrl)

to download the file directly from the CDN, however, if the file is not found, it ends up redirecting and responding 404. When I check the response object (I think it's just the redirect object), I just get the 302 of the redirect.

EDIT: I've tried calling

response()->download($externalUrl)

but that doesn't work at all.

How do I capture that response so that I may move on to serving the file locally, or is that even possible?

0 likes
2 replies
tykus's avatar

If your external resource allows it, you could use the Http Client to send a HEAD request to check that the resource exists before trying to send the user to that URL, e.g.:

use Illuminate\Support\Facades\Http;
 
$response = Http::head($externalUrl);

if ($response->getStatusCode() === 200) {
   return redirect()->away($externalUrl);
}

return response()->download('path/to/file');
martinbean's avatar

@zorkwarrior You’d have more luck if you just used Laravel’s filesystem component as intended. That way you wouldn’t need to do all these unnecessary checks for existence on CDNs, which are just going to be come a pain if you change CDNs, or add multiple CDNs.

Store which “disk” your file is located and the path:

$table->string('disk'); // local, s3, custom_cdn, etc.
$table->string('path');

And then your controller is a simple one-liner that doesn’t need to be updated each time you add/remove a CDN option:

return Storage::disk($file->disk)->download($file->path);

This also means you’re strongly adhering to SRP (single responsibility principle) as you don’t need to change your download controller action just because you happened to add/change/remove an external CDN provider.

Please or to participate in this conversation.