使用 laravel 中的前缀自定义 URL

Customizing URLs with prefix in laravel

我有这个html:

<ul>
   <li><a href="index.php/Page1">Page 01</a></   
   <li><a href="index.php/Page2">Page 02</a></li>
   <li><a href="index.php/Page3">Page 03</a></li>
</ul>  

如您所见,由于我大学的服务器需要在所有链接中使用index.php/前缀
(我不能改变它)。上面的方法,从主页直接到任何页面都可以正常工作,但是如果我尝试从另一个页面访问一个页面,我会得到错误的 URL 并且无法访问该页面:

示例:

主页
http://localhost/php-project/public/

第 1 页(来自国内)
来自:http://localhost/php-project/public/
收件人:http://localhost/php-project/public/index.php/Page1

第 2 页(来自国内)
来自:http://localhost/php-project/public/
收件人:http://localhost/php-project/public/index.php/Page2

第 1 页(来自第 2 页)
来自:http://localhost/php-project/public/index.php/Page2
收件人:http://localhost/php-project/public/index.php/index.php/Page1

如您所见,前缀重复了自己。我不知道该怎么做才能正常工作。

有什么想法吗?

您可以使用路由前缀。

Route::group(['prefix'=>'/index.php/'], function()
{
    Route::get('/', ['as'=>home, 'uses'=>'HomeController@index']);
    //Include all your routes here. And in your view, link any page with the route name. 
    // eg: <a href="{{URL::route('home')}}"></a>
});

这就是我解决问题的方法:

  • 我在 laravel 的 helper.php
  • 上创建了一个辅助函数

function custom_url($routename) { return str_replace("index.php", "",URL($routename)); }

并像这样使用:

<ul>
     <li><a href="{{custom_url('index.php/Page1')}}">Importar Histórico</a></li>
     <li><a href="{{custom_url('index.php/Page2')}}">Alocar Disciplina</a></li>    
</ul>

您可以使用 class Illuminate\Routing\UrlGenerator 上的方法 forceRootUrl 进行设置。

示例:

// app/Providers/AppServiceProvider
public function boot()
{
    // Instance of Illuminate\Routing\UrlGenerator
    $urlGenerator = $this->app['url'];

    // Instance of Illuminate\Http\Request
    $request = $this->app['request'];

    // Grabbing the root url
    $root = $request->root();

    // Add the suffix
    $rootSuffix = '/index.php';
    if (!ends_with($root, $rootSuffix)) {
        $root .= $rootSuffix;
    }

    // Finally set the root url on the UrlGenerator
    $urlGenerator->forceRootUrl($root);
}