2016-11-04



If you moved your site to a new domain, chances are you want the users and search engines to be directed to the correct pages on the new domain.

One way to do that is using 301 permanent redirects from old pages locations to the new pages locations. In Laravel you can define this in teh routes file like this:

If you have a lot of these they can quickly fill up your routes file and if you are using dynamic pages it could get unwieldy. Spatie’s new Laravel missing page redirector package aims to make this process easier by adding your redirects to the package config file or by implementing the included Redirector interface. Let’s take a look at how this package can be set up and used.

Installation

First, install Laravel missing page redirector through Composer:

Add its Service provider in config/app.php:

Then register the Spatie\MissingPageRedirector\RedirectsMissingPages middleware in app/Http/Kernel.php:

Then, you have to publish the config file, run the following command in your terminal:

Overview

If you opened config/laravel-missing-page-redirector.php configuration file, you will see the following:

First, you can change the source for your redirects to another source (for example a database) by creating your own redirector, the new redirector must implement Spatie\MissingPageRedirector\Redirector\Redirector interface and have getRedirectsFor method that returns an array maps the old URLs to the new URLs.

The second option is for specifying the redirects array for ConfigurationRedirector,  just add an element for each redirect with the old URL as the key and the new URL as the value of the element.

You can use route parameters by wrapping them between curly braces like this '/old-blog/{url}' => '/new-blog/{url}' and you can make it optional using question mark like this: '/old-blog/{url?}' => '/new-blog/{url}',.

Be aware that if you want to redirect an old URL to a new URL a different domain you must add http:// or https:// before the new URL like this: '/old-page' => 'https://laravel-news.com.

If you want an easy way to do 301 permanent redirects from old URLs to new URLs, give the Laravel missing page redirector a try.

Show more