首页 > 解决方案 > 显示存储在 laravel storage/app/protected/images 中的图像但返回 404

问题描述

该应用程序将图像存储在 Laravel 7 上 storage/app/protected/images 目录内的各种目录中。我在本地主机上显示从这些目录检索到的图像没有问题,但是当我移动到暂存时,我注意到每个请求都会返回404 即使图像显示在浏览器中。

我已经检查了后端,并且后端(管理员)中的所有图像都有相同的问题。

图片 URL 结构很简单:example.com/images/slider/image-name.png

这是我的ImageViewController

namespace App\Http\Controllers\Client;

    use App\Exceptions\ErrorPageException;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use Illuminate\Support\Facades\Storage;

    class ImageViewController extends Controller
    {
        public function getMainImage($name)
        {
            if(file_exists(storage_path('app/protected').'/images/'.$name)){
                $image = storage_path('app/protected').'/images/'.$name;
            }else{
                throw new ErrorPageException(404);
            }
            return response()->file($image);
        }

        public function getImage($type, $name)
        {
            if(file_exists(storage_path('app/protected').'/images/'.$type.'/'.$name)){
                $image = storage_path('app/protected').'/images/'.$type.'/'.$name;
            }else{
                throw new ErrorPageException(404);
            }
            return response()->file($image);
        }

    }

这是我的路线:

Route::get('images/{name}', 'Client\ImageViewController@getMainImage');

Route::get('images/{type}/{name}', 'Client\ImageViewController@getImage');

我似乎无法自己解决问题。

请帮忙!

标签: imagehttp-status-code-404laravel-7forge

解决方案


解决了!

包含 NGINX 静态文件缓存指令后出现问题。

我改变了方法,现在一切正常!

它们适用于我这种情况的任何人:

# browser caching of static assets
    location ~ /\.(jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ {
        expires 30d;
        add_header Pragma public;
        add_header Cache-Control "public";
    }

    # CSS and Javascript
    location ~* \.(?:css|js)$ {
      expires 1y;
      access_log off;
      add_header Cache-Control "public";
    }

所有这些代码都在server { ... }


推荐阅读