Creating a table for storing redirects. Also add an additional field for HTTP status
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRedirectsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('redirects', function (Blueprint $table) {
$table->increments('id');
$table->string('url_from', 191);
$table->string('url_to', 191)->nullable();
$table->smallInteger('status', 191)->unsigned()->default(301);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('redirects');
}
}
Creating Redirect Model
<?php
namespace App\Models\Seo;
use Illuminate\Database\Eloquent\Model;
class Redirect extends Model
{
protected $fillable = [
'url_from',
'url_to',
'status'
];
}
Add to app\Http\Kernel.php a new Middleware Class RedirectCustom
protected $middlewareGroups = [
'web' => [
...
\App\Http\Middleware\RedirectCustom::class
...
],
'api' => [
...
],
];
Create RedirectCustom Middleware Class
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class RedirectCustom
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
// Request string without GET arguments
$url = $request->getRequestUri();
// Get csv
$redirects = Cache::rememberForever('redirects', function () use ($csvPath) {
return Redirect::all();
});
// Redirect
foreach ($redirects as $redirect) {
//
if ($redirect->status == 410) {
header("HTTP/1.1 410 Gone");
exit();
}
if ($url == $redirect->url_from) {
header("Location: " . $redirect->url_to, TRUE, $redirect->status);
exit();
}
}
return $next($request);
}
}
redirects
to array and save it in cache with key 'redirects'