Laravel 5.8迁移至Apache 2服务器后存储目录图片显示异常
解决Laravel 5.8存储目录图片无法显示问题
排查方向与解决方案
1. 检查文件权限
- 确保
storage目录及子目录的权限设置正确,Apache进程需要有读取权限:
注:chmod -R 755 storage/ chown -R www-data:www-data storage/www-data是Apache默认运行用户,部分服务器可能为apache或httpd,需根据实际情况调整。
2. 验证MIME类型获取逻辑
自定义的\App\Library\File::getFileType($path)可能存在异常,建议替换为Laravel内置的文件类型检测排除干扰:
Route::get('/assets/img/{name?}', function ($name = null) { if (is_null($name)) { abort(404); } $path = storage_path('img/' . $name); if (!\File::exists($path)) { abort(404); } $mime_type = \Illuminate\Support\Facades\Storage::mimeType($path); return response()->file($path, ['Content-Type' => $mime_type]); })->where('name', '.+');
3. 确认Apache重写规则
- 检查项目根目录
.htaccess文件是否包含正确的Laravel重写规则:<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> - 确保Apache已启用
mod_rewrite模块:a2enmod rewrite systemctl restart apache2
4. 测试路由响应
直接访问图片路由(如http://你的域名/assets/img/test.jpg),查看浏览器控制台网络请求状态:
- 若返回404:确认
storage/img/下存在对应文件,且文件名(含大小写)与请求完全一致 - 若返回200但图片不显示:检查响应头的
Content-Type是否正确,可临时注释自定义MIME类型代码,使用response()->file($path)默认处理测试
5. 重新创建存储软链(可选)
虽已执行php artisan storage:link,可尝试先删除现有软链再重建:
rm public/storage php artisan storage:link
注:当前路由通过assets/img映射,软链可能不是核心问题,但确保其创建正确无负面影响。
内容的提问来源于stack exchange,提问作者idir
相关产品推荐
相关产品推荐

