自定义带有 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

如您所见,前缀会自行重复。我不知道如何做到这一点才能正常工作。

有什么想法吗?

您可以使用

Illuminate'Routing'UrlGeneratorforceRootUrl的方法进行设置。

例:

// 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);
}

您可以使用路由前缀。

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>