Laravel loại bỏ /index.php/ trên URL tối ưu SEO
Như ở bài viết trước Laravel Nginx loại bỏ /index.php/ trên URL tối ưu SEO thì gần như hầu hết các website Laravel hiện nay dính lỗi đó là có index.php trong URL. Đơn cử như trang web laravel.com https://laravel.com/docs/6.x/validation https://laravel.com/index.php/docs/6.x/validation ...
Như ở bài viết trước Laravel Nginx loại bỏ /index.php/ trên URL tối ưu SEO thì gần như hầu hết các website Laravel hiện nay dính lỗi đó là có index.php trong URL. Đơn cử như trang web laravel.com
https://laravel.com/docs/6.x/validation
https://laravel.com/index.php/docs/6.x/validation
Thông thường sẽ k ảnh hưởng tới người dùng vì URL có index.php k xuất hiện nhưng sẽ ảnh hưởng tới SEO vì google vẫn xác định đây là 2 url riêng biệt.
Mình viết thêm bài này vì có một số bạn không chạy trên nginx hoặc k có quyền chỉnh sửa cài đặt trên webserver thì bạn chỉ cần chỉnh sửa 1 tí trong file appProvidersRouteServiceProvider.php
<?php
namespace AppProviders;
use IlluminateFoundationSupportProvidersRouteServiceProvider as ServiceProvider;
use IlluminateSupportFacadesRoute;
use Str;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'AppHttpControllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
$this->removeIndexPhpFromUrl();
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
/**
* This will remove the index.php from the URL and prevent canonical conflicts.
*
* @return void
*/
protected function removeIndexPhpFromUrl()
{
if (Str::startsWith(request()->getRequestUri(), '/index.php')) {
$url = str_replace('/index.php', ', request()->getRequestUri());
$url = request()->getSchemeAndHttpHost() . Str::start($url, '/');
if (strlen($url) > 0) {
header("Location: $url", true, 301);
exit;
}
}
}
}