01:如何将资源文件夹放在pulic外
如css放在 /statics/assets/cms/css/main.css
<link href="http://www.abc.app/assets/cms/css/app.min.css" rel="stylesheet">
解决过程:
app.min.css这个文件的请求也是经过public/index.php,看下$_SERVER
中有关路径的内容如下
[server] => Symfony\Component\HttpFoundation\ServerBag Object(
[parameters:protected] => Array(
[HTTP_HOST] => www.abc.app
[SERVER_NAME] => abc.app
[DOCUMENT_ROOT] => /home/vagrant/abcde/study/abc/public
[DOCUMENT_URI] => /index.php
[REQUEST_URI] => /assets/cms/css/app.min.css
[SCRIPT_NAME] => /index.php
[SCRIPT_FILENAME] => /home/vagrant/abcde/study/abc/public/index.php
...
)
...
)
有两个解决办法,一个是在.htaccess中定义规则,另一个就是在全局中间件中生成响应对象直接返回
下面是第二种解决办法,定义中间件
第一步:定义全局中间件
class StaticPath{
protected $container;
protected $response;
// 根据扩展名定义内容类型,完整参考 \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser::$defaultExtensions
protected $mimes = [
'css' => 'text/css',
'html' => 'text/html',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'js' => 'application/x-javascript',
];
public function __construct(Container $container, ResponseFactory $response){
$this->container = $container;
$this->response = $response;
}
public function handle($request, Closure $next){
$staticPath = base_path('statics'); //获取static的目录
$file = staticPath . DIRECTORY_SEPARATOR . $request->path(); //请求文件的实际路径, /home/vagrant/abcde/study/abc/statics/assets/install/css/app.min.css
if (file_exists($file) && !Str::endsWith('/', $request->path())) { //如果文件存在,就直接返回象
//指定headers
$headers = [];
$extension = pathinfo($file, PATHINFO_EXTENSION); //文件扩展名
if (isset($this->mimes[$extension])) {
$headers['Content-Type'] = $this->mimes[$extension];
} else {
$headers['Content-Type'] = 'application/octet-stream';
}
//返回请求对象
return $this->response->make(file_get_contents($file), 200, $headers);
} else {
return $next($request);
}
}
}
第二步:配置中间件
方法一:直接在App/Http/Kernel中配置
protected $middleware = [
...\Middleware\StaticPath::class,
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
方法二:在任一服务提供商中
在AppHttpKernel中的$middleware最前面增加中间件StaticPath
$this->app->make(KernelContract::class)->prependMiddleware(StaticPath::class);
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。