Laravel - append a trailing slash in routes

2019-03-31 18:56发布

As I mentioned several times here, I'm redoing one of my old sites with Laravel.

Another problem I encounter is the following :

  • I've got mainly two different types of urls on the old website :
    • /user-slug/ for the users homepage, and
    • /user-slug/content-slug.html for one of its content

I managed to recreate the second one, but Laravel always trims the last slash when I try to create a link to the user route, and I end with an url like /user-slug

I don't want to lose any SEO when switching the old website to Laravel, so I wanted to know whether it was possible to force Laravel to append the trailing slash on one url ?


My code so far:

app\Providers\RouteServiceProvider.php :

public function boot(Router $router)
{
    $router->pattern('user', '[a-zA-Z0-9_-]+');
    $router->pattern('content', '[a-zA-Z0-9_-]+');
    parent::boot($router);
}

app\Http\routes.php :

Route::group(['middleware' => ['web']], function () {
    Route::get('/', [
        'as'   => 'index',
        'uses' => 'BaseController@index',
    ]);

    Route::get('/{user}/', [
        'as'   => 'user',
        'uses' => 'UserController@show',
    ]);

    Route::get('/{user}/{content}.html', [
        'as'   => 'content',
        'uses' => 'ContentController@show',
    ]);
});

views/home.blade.php :

{!! Html::linkRoute('user', $content['user']['name'], [$content->user->slug]) !!}

If there is no workaround, I'll use a .htaccess file to redirect all /user-slug/ urls to /user-slug, but if I can avoid it, that would be cool.

0条回答
登录 后发表回答