LoginSignup
8
3

More than 5 years have passed since last update.

Laravel5.6 URL変更に伴うリダイレクトのベストプラクティス

Posted at

はじめに

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.phpRedirects/ArticlesController.phpshowアクションを参照するようにしたので、コントローラーを作成します。

以下で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でリダイレクト出来るようになります。

最後に

ベストプラクティスと書いていますが、色々ツッコミどころ満載かと思いますので、何かあれば、優しいコメントいただけますと幸いです。。

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3