はじめに
URL変更に伴い、SEOの効果を引き継ぎつつリダイレクト処理を書かないといけない。
そんな時のベストプラクティスを考えて見ました。
こちらの記事と近い内容になっていますので、合わせて確認して見てください。
環境
- PHP7.1
- Laravel5.6
やりたいこと
- 静的URLにも動的URLにも対応する必要がある
- webサーバー(Apache or Nginx)に依存せず、リダイレクトをやりたい。
- HTTPステータスコードを301で返す
つまりはLaravel側でやっちゃいたいということです
RouteServiceProvider.php
リンクした記事でも紹介しましたが、app/Providers/RouteServiceProvider.php
を拡張します
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Route;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
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 = 'App\Http\Controllers';
/**
* 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->mapRedirectRoutes();
$this->mapApiRoutes();
$this->mapWebRoutes();
}
// 以下を追加
protected function mapRedirectRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/redirect.php'));
}
/**
* 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'));
}
}
こちら補足しますと、ルーティングは定義する順番によって優先度が決まるので、web.php
よりも先にredirect.php
のルーティングが優先されるようにしています。
redirect.php
routes
ディレクトリの中にredirect.php
を作成します。
<?php
あとはRoute::redirect
メソッドを使ってリダイレクト処理を書いてあげるだけです。
Route::redirect
メソッドの引数の文法は以下です。
<?php
Route::redirect('from', 'to', HTTPステータスコード);
静的URLのリダイレクト
redirect.php
に追記します。
例えば、/hoge
というurlにアクセスがあったら、/poge
にリダイレクトをさせたい場合は以下のようになります。
<?php
Route::redirect('/hoge', '/poge', 301);
動的URLのリダイレクト
例えば、/posts/12
を/articles/12
などのようにidは動的になるようなURLをリダイレクトさせたい場合は、以下です。
redirect.php
<?php
Route::get('/posts/{id}', 'Redirects\ArticlesController@show');
Redirects/ArticlesController.php
redirect.php
でRedirects/ArticlesController.php
のshow
アクションを参照するようにしたので、コントローラーを作成します。
以下で
app/Http/Controller/Redirects
のサブディレクトリにコントローラーを作成出来ます。
$ php artisan make:controller "Redirects\ArticlesController"
作成したら、app/Http/Controller/Redirects/ArticlesController.php
を以下を追記します。
public function show($id)
{
return redirect('/articles/'.$id, 301);
}
以上で動的にHTTPステータスコード301でリダイレクト出来るようになります。
最後に
ベストプラクティスと書いていますが、色々ツッコミどころ満載かと思いますので、何かあれば、優しいコメントいただけますと幸いです。。