正如我在这里多次提到的那样,我正在用Laravel重做我的一个旧网站。
我遇到的另一个问题如下:
/user-slug/
,/user-slug/content-slug.html
了解其中一项内容我设法重新创建了第二个,但是当我尝试创建一个指向用户路径的链接时,Laravel总是修剪最后一个斜线,最后我得到一个像/user-slug
我不想在将旧网站切换到Laravel时丢失任何搜索引擎优化,所以我想知道是否有可能强制Laravel在一个网址上附加尾部斜杠?
到目前为止我的代码:
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]) !!}
如果没有解决方法,我会使用.htaccess
文件将所有/user-slug/
个网址重定向到/user-slug
,但如果我可以避免,那就太酷了。
答案 0 :(得分:0)
嗯,我认为通过中间件看起来很可能。
$ php artisan make:middleware slashesMiddleware
转到 app / Http / Middleware / slashesMiddleware.php ,并用此内容填充
<?php
namespace App\Http\Middleware;
use Closure;
class slashesMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $flag)
{
if ($flag=="remove") {
if (ends_with($request->getPathInfo(), '/')) {
$newval = rtrim($request->getPathInfo(), "/");
header("HTTP/1.1 301 Moved Permanently");
header("Location:$newval");
exit();
}
} else {
if (!ends_with($request->getPathInfo(), '/')) {
$newval =$request->getPathInfo().'/';
header("HTTP/1.1 301 Moved Permanently");
header("Location:$newval");
exit();
}
}
return $next($request);
}
}
此添加2种方法首先“添加” 尾部斜线进行路由或“删除”
将其添加到您的应用中间件列表中,并转到 $ routeMiddleware
下的 app / Http / Kernel.php 。 protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'slashes' => \App\Http\Middleware\slashesMiddleware::class,
];
用法示例
Route::get('/compare', 'WebRouteController@compare')->middleware("slashes:add");