如css放在 /statics/assets/cms/css/main.cssjavascript
<link href="http://www.abc.app/assets/cms/css/app.min.css" rel="stylesheet">
解決過程:
app.min.css這個文件的請求也是通過public/index.php,看下$_SERVER
中有關路徑的內容以下php
[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中定義規則,另外一個就是在全局中間件中生成響應對象直接返回
下面是第二種解決辦法,定義中間件css
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中配置html
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最前面增長中間件StaticPathjava
$this->app->make(KernelContract::class)->prependMiddleware(StaticPath::class);