如何在Laravel中为DigitalOcean私有Spaces生成临时访问URL
解决DigitalOcean Spaces在Laravel中生成临时签名链接的问题
首先确认已安装S3驱动依赖,生产环境执行下述命令安装:composer require league/flysystem-aws-s3-v3 "^3.0"
然后修改config/filesystems.php配置文件中的Spaces存储盘配置,必须指定driver为s3,DO Spaces完全兼容S3 API,无需自定义驱动,完整配置参考:
'spaces' => [ 'driver' => 's3', 'key' => env('DO_SPACES_KEY'), 'secret' => env('DO_SPACES_SECRET'), 'region' => env('DO_SPACES_REGION'), 'bucket' => env('DO_SPACES_BUCKET'), 'endpoint' => env('DO_SPACES_ENDPOINT'), 'use_path_style_endpoint' => false, 'visibility' => 'private', ],
参数说明:
- region填写你创建Space时选择的区域,例如
nyc3、sgp1 - endpoint格式为
https://<区域>.digitaloceanspaces.com,不要在域名前拼接bucket名称
配置修改后执行命令清空生产环境配置缓存:php artisan config:cache
后续直接调用原生temporaryUrl方法即可生成带签名的临时访问链接,示例:
// 生成1小时有效期的私有资源临时访问链接 $temporaryUrl = Storage::disk('spaces')->temporaryUrl( '你的私有文件路径.jpg', now()->addHour() );
如果需要自定义响应行为,例如强制下载,可以传入第三个参数配置:
$temporaryUrl = Storage::disk('spaces')->temporaryUrl( '你的私有文件路径.jpg', now()->addHour(), ['ResponseContentDisposition' => 'attachment'] );
生成的链接自带合法签名,有效期内可直接访问私有资源,不会返回Access Denied错误。
内容的提问来源于stack exchange,提问作者Alexa
相关产品推荐
相关产品推荐

