How do I remove /storage from the URL for public images in my Laravel project?

試著忘記壹切 提交于 2019-12-11 05:37:56

问题


What I am trying to achieve is to remove the /storage from the URL, so that in the end it is www.example.com/images/x.jpg and not the default www.example.com/storage/x.jpg.

I have tried removing /storage from the url in config/filesystems.php like this:

// Original

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

// Modified

'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL'), // <-- changed
        'visibility' => 'public',
 ],

but it is not working. I think the issue is that without a prefix it will be regarded as file inside a public folder.

Is it possible to achieve what i am trying to achieve?


回答1:


The best way to achieve this is to add a new images disk. This way the new url pattern can be applied selectively and it will not interfere with any of your existing code.

Step 1

Add your disk to config/filesystems.php:

'images' => [
        'driver' => 'local',
        'root' => storage_path('app/public/images'),
        'url' => env('APP_URL') . '/images',
        'visibility' => 'public',
 ],

This is how you save file uploads to your new disk:

$request->file('image')->storeAs(/* path */ '/', /* filename */ 'x.jpg', /* disk */ 'images')

And this is how you create links to the image that look like http://example.com/images/x.jpg:

Storage::disk('images')->url('x.jpg')

Step 2

Now that you can create links to these images, you have to make sure your server can find them. You have multiple options for this.

Option 1

Create a symlink in your public directory, which is how Laravel's default public disk (/storage) works.

$ ln -s /var/www/example.com/storage/app/public/images /var/www/example.com/public/images

Option 2

Create a route in your Laravel application to serve images.

Route::get('images/{file}', function ($file) {
    return Storage::disk('images')->response($file);
    // return Storage::disk('images')->download($file);
});

Option 3

Create a rewrite rule in your webserver.

In nginx, it might look like this:

location /images/ {
    root /var/www/example.com/storage/app/public/;
}

In Apache, you might use an alias:

Alias "/images" "/var/www/example.com/storage/app/public/images"


来源:https://stackoverflow.com/questions/54495420/how-do-i-remove-storage-from-the-url-for-public-images-in-my-laravel-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!