如何路由到 Laravel 中的静态文件夹

How to route to a static folder in Laravel

我在 Laravel 站点的 /public 文件夹中有一个文件夹。路径是:

/public/test

"test" 文件夹有一个名为 index.html 的文件,它只是我想从 public 文件夹加载的静态资源(我不想为创建视图这在框架内——太多了,无法解释。

我做了这样的路线:

Route::get('/test', function() {
  return File::get(public_path() . '/test/index.html');
});

我无法让它工作。我刚从 Chrome 收到一条错误消息,说这个页面有一个重定向循环。

我可以这样访问:

http://www.example.com/test/index.html

但我无法在任何地方使用 .html 扩展名。该文件必须显示为:

http://www.example.com/test/

如何在不使用 .html 扩展名的情况下从 Laravel public 文件夹提供单个 HTML 页面?

使用:

return Redirect::to('/test/index');

在你的路由文件或控制器内部的函数中。

以前遇到过这个问题,作为一个肮脏的小技巧,您可以将测试文件夹重命名为其他名称然后更新

return File::get(public_path() . '/to new folder name/index.html');

关键是你的路由 url 与你在 public

中的文件夹没有冲突

对于静态文件,我认为您通过 Laravel 为它提供服务是在浪费资源。

过去在 public 中尝试访问 files/folders 时存在一些错误,导致无限重定向,但我认为 Laravel 附带的最新 .htaccess 已解决这些问题(至少在 Apache 上)。看起来像这样

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ / [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

它说'如果请求不是针对现有文件夹,如果有,则去掉尾部斜杠。如果请求不是针对现有文件夹或现有文件,请加载 Laravel's index.php'

然后我在子目录中添加了一个 .htaccess 文件,以确保设置了 DirectoryIndex,以便在请求目录时默认加载 index.html。