自定义laravel中带有前缀的URL

时间:2016-02-05 22:04:03

标签: php laravel url-routing

我有这个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/

Page1 (来自家庭)
来自:http://localhost/php-project/public/
TO:http://localhost/php-project/public/index.php/Page1

Page2 (来自家庭)
来自:http://localhost/php-project/public/
TO:http://localhost/php-project/public/index.php/Page2

Page1 (来自第2页)
来自:http://localhost/php-project/public/index.php/Page2
TO:http://localhost/php-project/public/index.php/index.php/Page1

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

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

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

示例:

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

答案 1 :(得分:1)

您可以使用路线前缀。

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

答案 2 :(得分:0)

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

  • 我在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>