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

ronmakeszens's avatar

How to get Storage::TemporaryUrl($url, $expires) cacheable?

When using S3 storage (DigitalOcean Spaces, in this case) to get pre-signed Url's, the Storage facade generates different Urls even when the params are the same.

Even when setting the same $expires value (15 min), somehow this seems translated into a different x-amz-date/x-amz-expires combination each second; seemingly expiration is triggered by these two parameters.

Not having the same URL prevents caching in the browser, so I would like to have stable pre signed Urls for 15 minutes. Are there any options to accomplish this, for instance by rounding x-amz-date or even skipping this? Or is this deeply part of the S3 architecture?

For my case, I don't want the proxy/redirect approach due to the additional load on the server it causes, and I need the short lived URLs for security reasons.

0 likes
1 reply
LaryAI's avatar
Level 58

One possible solution is to use a cache layer to store the generated URLs and serve them from cache instead of generating a new URL every time. This can be achieved using Laravel's Cache facade. Here's an example code snippet:

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;

$url = 'path/to/file';
$expires = now()->addMinutes(15);

// Check if the URL is already cached
if (Cache::has($url)) {
    $temporaryUrl = Cache::get($url);
} else {
    // Generate a new temporary URL and cache it
    $temporaryUrl = Storage::temporaryUrl($url, $expires);
    Cache::put($url, $temporaryUrl, );
}

// Use the cached or newly generated URL
echo $temporaryUrl;

This code checks if the URL is already cached using Laravel's Cache facade. If it is, it retrieves the cached URL and uses it. If not, it generates a new temporary URL using Laravel's Storage facade and caches it for 15 minutes using the Cache facade. This way, subsequent requests for the same URL will use the cached URL instead of generating a new one every time.

Please or to participate in this conversation.