如何在Laravel项目中从公共图像的URL中删除/存储? [英] How do I remove /storage from the URL for public images in my Laravel project?
问题描述
我要实现的是从URL中删除/storage,以便最后是www.example.com/images/x.jpg
而不是默认的www.example.com/storage/x.jpg
.
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
.
我试图像这样从config/filesystems.php
中的url
中删除/storage:
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?
推荐答案
实现此目的的最佳方法是添加新的images
磁盘.这样,可以有选择地应用新的网址格式,并且不会干扰您现有的任何代码.
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.
将磁盘添加到 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')
这是您创建类似于http://example.com/images/x.jpg
的图像的链接的方法:
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')
步骤2
现在您可以创建指向这些图像的链接,因此必须确保您的服务器可以找到它们.为此,您有多种选择.
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.
在公共目录中创建符号链接,这是Laravel的默认public
磁盘(/storage
)的工作方式.
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
选项2
在Laravel应用程序中创建一条路线以投放图像.
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);
});
选项3
在您的网络服务器中创建重写规则.
Option 3
Create a rewrite rule in your webserver.
在nginx中,它可能看起来像这样:
In nginx, it might look like this:
location /images/ {
root /var/www/example.com/storage/app/public/;
}
在Apache中,您可以使用别名:
In Apache, you might use an alias:
Alias "/images" "/var/www/example.com/storage/app/public/images"
这篇关于如何在Laravel项目中从公共图像的URL中删除/存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!