You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10如何去除URL中的/storage直接访问存储图片?

解决Laravel 10图片访问路径去掉/storage前缀的问题

核心原因

你修改FILESYSTEM_DISK为public没用,是因为这个配置只决定文件存储的目标磁盘,不影响访问路径的前缀。默认public磁盘的URL前缀是/storage,这由filesystems.php里的url配置项控制,同时需要服务器配合转发请求到实际文件路径。

解决方案一:修改文件系统配置+服务器重写规则

1. 调整filesystems.php的public磁盘配置

打开config/filesystems.php,找到public磁盘的配置,把url项从env('APP_URL').'/storage'改成env('APP_URL'):

'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'),
    'url' => env('APP_URL'), // 去掉/storage后缀
    'visibility' => 'public',
],

之后调用Storage::disk('public')->url('user.name/image.jpg')时,生成的URL就是http://localhost:8000/user.name/image.jpg。

2. 配置服务器重写规则

实际文件存在public/storage/user.name/image.jpg(由storage:link生成的符号链接),需要服务器把/user.name/image.jpg的请求转发到/storage/user.name/image.jpg。

Apache环境(修改public/.htaccess)

在现有的RewriteRule ^ index.php [L]之前添加:

# 匹配user.name/xxx格式的请求,转发到storage目录
RewriteRule ^([a-zA-Z0-9.]+/.*)$ storage/$1 [L]

Nginx环境(修改站点配置)

在server块内添加:

location ~ ^/[a-zA-Z0-9.]+/ {
    try_files $uri $uri/ /storage$uri;
}

解决方案二:用Laravel路由直接处理

如果不想改服务器配置,可以在routes/web.php中添加路由规则,直接匹配并返回图片:

Route::get('{username}/{filename}', function ($username, $filename) {
    $filePath = "{$username}/{$filename}";
    // 检查文件是否存在
    if (!Storage::disk('public')->exists($filePath)) {
        abort(404);
    }
    // 返回文件响应
    return Storage::disk('public')->response($filePath);
})->where([
    'username' => '[a-zA-Z0-9.]+', // 匹配包含点的用户名格式
    'filename' => '[a-zA-Z0-9._-]+' // 匹配常见的文件名格式
]);

访问http://localhost:8000/user.name/image.jpg时,路由会直接从存储磁盘读取文件并返回。

注意事项

  • 不要直接将storage/app/public符号链接到public根目录,这会覆盖public下的index.php、静态资源等核心文件,导致应用崩溃。
  • 若使用方案一,修改配置后需要清除配置缓存:php artisan config:clear

内容的提问来源于stack exchange,提问作者JuniorDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 07:42:37