我已经将图像上传到S3,现在在html中我想简单地检索它们,所以我做了:
<a href="{{ url('/') }}">
<img class="navbar-brand" src="https://s3.eu-west-2.amazonaws.com/production/public/images/logo-small.png">
</a>
但是,图像不显示,如果我将链接放在浏览器中,我会得到:
公共/图像/徽标小.png
而不是实际图像。
我在这里做错了什么?
我遇到的另一个问题是我所有的 css 和 js 都有
{{ asset('path/to/file') }}
在本地工作正常,但在我的网络服务器上无法正常工作,因为它在我的服务器 https://时给了我 http://domain
现在,如果我将资产更改为secure_asset,它可以工作,但是在本地它不起作用,因为我的本地构建显然不安全。
如何解决这两个问题?
第二个问题的答案是使用 HTTP 和 HTTPS 重定向。
使用env('APP_ENV')
检查您的工作环境并相应地设置条件。要实现这一点,只需创建一个中间件,并根据环境重定向 URL 与HTTPS or HTTP
.
如果您使用的是Laravel 5+
.
下面是中间件的示例:
<?php namespace AppHttpMiddleware;
use Closure;
use IlluminateContractsRoutingMiddleware;
/**
* Secure
* Redirects any non-secure requests to their secure counterparts.
*
* @param request The request object.
* @param $next The next closure.
* @return redirects to the secure counterpart of the requested uri.
*/
class Secure implements Middleware
{
public function handle($request, Closure $next)
{
$secureEnvs = ['dev', 'qa', 'stage', 'prod'];
$isSecureEnv = in_array(env('APP_ENV'), $secureEnvs);
$requestNotSecure = $request->header('x-forwarded-proto') !== 'https';
// If environment is secure and request is not redirect
if ($isSecureEnv && $requestNotSecure) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
}
在$routeMiddleware
数组中添加此中间件的条目。
Okey,首先,不需要调用public
目录,因为是服务器的默认根目录,所以你的 url 看起来像这样:
图片/徽标小.png
asset(( 帮助程序函数,如文档所述:
使用请求的当前方案为资产生成 URL (HTTP 或 HTTPS(
因此,您可能需要更改请求方案,也检查.env
文件,APP_URL
字段是使用 https 设置的。
最后,我建议您将 s3 设置为存储磁盘,以便您可以像这样调用帮助程序:
use IlluminateSupportFacadesStorage;
$url = Storage::url('file.jpg');
作为附加信息,当我的文件不公开时,我过去曾遇到过 s3 问题,所以我无法通过 url 访问它们,如果设置为公共,请检查 s3 面板中的文件配置,您也可以在同一面板上检查其 URL。
希望这对你有帮助。