Laravel custom middleware for 301 redirection to non index.php url
In this post we will give you information about Laravel custom middleware for 301 redirection to non index.php url. Hear we will give you detail about Laravel custom middleware for 301 redirection to non index.php urlAnd how to use it also give you demo for it if it is necessary.
In this Laravel PHP tutorial, I will let you know how to remove index.php from the URL.
Having index.php
in the URL is not good for the SEO practice.
You can also use .htaccess
file to remove the index.php from the URL with 301 redirection but for this example, I will create a custom middleware.
Configure “RemoveIndexPhp” custom middleware
In this step, I will run PHP artisan command to create middleware :
php artisan make:middleware RemoveIndexPhp
After running above command, you will have a middleware file in following directory app/Http/Middleware/.
Now open “RemoveIndexPhp.php” file and update that with below code :
<?php namespace AppHttpMiddleware; use Closure; classRemoveIndexPhp { publicfunctionhandle($request, Closure $next) { $searchFor="index.php"; $strPosition=strpos($request->fullUrl(), $searchFor); if ($strPosition!==false) { $url= substr($request->fullUrl(), $strPosition+strlen($searchFor)); return redirect(config('app.url') .$url, 301); } return$next($request); } }
Now register this middleware as routeMiddleware in the Kernel.php
file.
app/Http/Kernel.php :
protected $routeMiddleware = [ .... 'RemoveIndexPhp' => AppHttpMiddlewareRemoveIndexPhp::class, ];
Add route
To test this example, I need to add a single route inside the group middleware :
Route::group(array('middleware' => ['RemoveIndexPhp']), function () { Route::get('/',function(){ return "Welcome to onlinecode"; }); });
Try this..
Hope this code and post will helped you for implement Laravel custom middleware for 301 redirection to non index.php url. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs
Wow this is good info. thanks.