Repository: spatie/laravel-missing-page-redirector Branch: main Commit: 6c75eb4c6870 Files: 27 Total size: 36.3 KB Directory structure: gitextract_eh6sh8rb/ ├── .editorconfig ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ └── config.yml │ └── workflows/ │ ├── php-cs-fixer.yml │ ├── run-tests.yml │ └── update-changelog.yml ├── .gitignore ├── .php-cs-fixer.dist.php ├── .phpunit.cache/ │ └── test-results ├── .phpunit.result.cache ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── composer.json ├── config/ │ └── missing-page-redirector.php ├── phpunit.xml.dist ├── src/ │ ├── Events/ │ │ ├── RedirectNotFound.php │ │ └── RouteWasHit.php │ ├── MissingPageRedirectorServiceProvider.php │ ├── MissingPageRouter.php │ ├── Redirector/ │ │ ├── ConfigurationRedirector.php │ │ └── Redirector.php │ └── RedirectsMissingPages.php └── tests/ ├── Pest.php ├── RedirectsMissingPagesTest.php └── TestCase.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ ; This file is for unifying the coding style for different editors and IDEs. ; More information at http://editorconfig.org root = true [*] charset = utf-8 indent_size = 4 indent_style = space end_of_line = lf insert_final_newline = true trim_trailing_whitespace = true [*.md] trim_trailing_whitespace = false ================================================ FILE: .gitattributes ================================================ # Path-based git attributes # https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html # Ignore all test and documentation with "export-ignore". /.gitattributes export-ignore /.gitignore export-ignore /.travis.yml export-ignore /phpunit.xml.dist export-ignore /.scrutinizer.yml export-ignore /tests export-ignore ================================================ FILE: .github/FUNDING.yml ================================================ custom: https://spatie.be/open-source/support-us ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: true contact_links: - name: Feature Request url: https://github.com/spatie/laravel-missing-page-redirector/discussions/new?category=ideas about: Share ideas for new features - name: Ask a Question url: https://github.com/spatie/laravel-missing-page-redirector/discussions/new?category=q-a about: Ask the community for help ================================================ FILE: .github/workflows/php-cs-fixer.yml ================================================ name: Check & fix styling on: [push] jobs: php-cs-fixer: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 with: ref: ${{ github.head_ref }} - name: Run PHP CS Fixer uses: docker://oskarstark/php-cs-fixer-ga with: args: --config=.php-cs-fixer.dist.php --allow-risky=yes - name: Commit changes uses: stefanzweifel/git-auto-commit-action@v4 with: commit_message: Fix styling ================================================ FILE: .github/workflows/run-tests.yml ================================================ name: run-tests on: - push - pull_request jobs: test: runs-on: ${{ matrix.os }} strategy: fail-fast: true matrix: os: [ubuntu-latest] php: [8.4, 8.3, 8.2, 8.1, 8.0] laravel: ['8.*', '9.*', '10.*', '11.*', '12.*', '13.*'] dependency-version: [prefer-stable] include: - laravel: 10.* testbench: 8.* - laravel: 9.* testbench: 7.* - laravel: 8.* testbench: 6.* - laravel: 11.* testbench: 9.* - laravel: 12.* testbench: 10.* - laravel: 13.* testbench: 11.* exclude: - laravel: 10.* php: 8.0 - laravel: 5.8.* php: 8.0 - laravel: 5.8.* php: 8.1 - laravel: 6.* php: 8.1 - laravel: 7.* php: 8.1 - laravel: 9.* php: 7.4 - laravel: 11.* php: 8.1 - laravel: 11.* php: 8.0 - laravel: 12.* php: 8.1 - laravel: 12.* php: 8.0 - laravel: 13.* php: 8.2 - laravel: 13.* php: 8.1 - laravel: 13.* php: 8.0 name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }} steps: - name: Checkout code uses: actions/checkout@v2 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php }} extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo coverage: none - name: Install dependencies run: | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction - name: Execute tests run: vendor/bin/pest ================================================ FILE: .github/workflows/update-changelog.yml ================================================ name: "Update Changelog" on: release: types: [released] jobs: update: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v2 with: ref: main - name: Update Changelog uses: stefanzweifel/changelog-updater-action@v1 with: latest-version: ${{ github.event.release.name }} release-notes: ${{ github.event.release.body }} - name: Commit updated CHANGELOG uses: stefanzweifel/git-auto-commit-action@v4 with: branch: main commit_message: Update CHANGELOG file_pattern: CHANGELOG.md ================================================ FILE: .gitignore ================================================ build composer.lock docs vendor .php_cs.cache .php-cs-fixer.cache ================================================ FILE: .php-cs-fixer.dist.php ================================================ in([ __DIR__ . '/src', __DIR__ . '/tests', ]) ->name('*.php') ->ignoreDotFiles(true) ->ignoreVCS(true); return (new PhpCsFixer\Config()) ->setRules([ '@PSR12' => true, 'array_syntax' => ['syntax' => 'short'], 'ordered_imports' => ['sort_algorithm' => 'alpha'], 'no_unused_imports' => true, 'not_operator_with_successor_space' => true, 'trailing_comma_in_multiline' => true, 'phpdoc_scalar' => true, 'unary_operator_spaces' => true, 'binary_operator_spaces' => true, 'blank_line_before_statement' => [ 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], ], 'phpdoc_single_line_var_spacing' => true, 'phpdoc_var_without_name' => true, 'class_attributes_separation' => [ 'elements' => [ 'method' => 'one', ], ], 'method_argument_space' => [ 'on_multiline' => 'ensure_fully_multiline', 'keep_multiple_spaces_after_comma' => true, ], 'single_trait_insert_per_statement' => true, ]) ->setFinder($finder); ================================================ FILE: .phpunit.cache/test-results ================================================ {"version":"pest_2.36.0","defects":[],"times":{"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_will_not_interfere_with_existing_pages":0.037,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_will_redirect_a_non_existing_page_with_a_permanent_redirect":0.017,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_will_redirect_wildcard_routes":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_will_not_redirect_an_url_that_is_not_configured":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_can_use_named_properties":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_can_use_multiple_named_parameters_in_one_segment":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_can_optionally_set_the_redirect_status_code":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_can_use_optional_parameters#('\/old-segment', '\/new-segment')":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_can_use_optional_parameters#('\/old-segment\/old-segment2', '\/new-segment\/old-segment2')":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_can_use_optional_parameters#('\/old-segment\/old-segment2\/old-segment3', '\/new-segment\/old-segment2\/old-segment3')":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_by_default_it_will_not_redirect_requests_that_are_not_404s":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_will_fire_an_event_when_a_route_is_hit":0.002,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_will_redirect_depending_on_redirect_status_code_defined":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_will_not_redirect_if_the_status_code_is_not_specified_in_the_config_file":0.001,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_will_redirect_on_any_status_code":0.049,"P\\Tests\\RedirectsMissingPagesTest::__pest_evaluable_it_will_fire_an_event_when_no_redirect_was_found":0.001}} ================================================ FILE: .phpunit.result.cache ================================================ {"version":1,"defects":{"\/Users\/alexandrumanase\/Documents\/repos\/laravel-missing-page-redirector\/tests\/RedirectsMissingPagesTest.php::it":4},"times":{"\/Users\/alexandrumanase\/Documents\/repos\/laravel-missing-page-redirector\/tests\/RedirectsMissingPagesTest.php::it":0.002,"\/Users\/alexandrumanase\/Documents\/repos\/laravel-missing-page-redirector\/tests\/RedirectsMissingPagesTest.php::by":0.002}} ================================================ FILE: CHANGELOG.md ================================================ # Changelog All notable changes to `laravel-missing-page-redirector` will be documented in this file ## 2.12.0 - 2026-02-21 Add Laravel 13 support ## 2.11.1 - 2025-02-21 ### What's Changed * Laravel 12.x Compatibility by @laravel-shift in https://github.com/spatie/laravel-missing-page-redirector/pull/88 **Full Changelog**: https://github.com/spatie/laravel-missing-page-redirector/compare/2.11.0...2.11.1 ## 2.11.0 - 2025-01-06 ### What's Changed * Update README.md by @hofmannsven in https://github.com/spatie/laravel-missing-page-redirector/pull/86 * Update README.md by @chengkangzai in https://github.com/spatie/laravel-missing-page-redirector/pull/85 * fix php8.4 nullable is deprecated by @it-can in https://github.com/spatie/laravel-missing-page-redirector/pull/87 ### New Contributors * @hofmannsven made their first contribution in https://github.com/spatie/laravel-missing-page-redirector/pull/86 * @chengkangzai made their first contribution in https://github.com/spatie/laravel-missing-page-redirector/pull/85 * @it-can made their first contribution in https://github.com/spatie/laravel-missing-page-redirector/pull/87 **Full Changelog**: https://github.com/spatie/laravel-missing-page-redirector/compare/2.10.0...2.11.0 ## 2.10.0 - 2024-03-12 ### What's Changed * Laravel 11.x Compatibility by @laravel-shift in https://github.com/spatie/laravel-missing-page-redirector/pull/84 **Full Changelog**: https://github.com/spatie/laravel-missing-page-redirector/compare/2.9.4...2.10.0 ## 2.9.4 - 2023-01-24 ### What's Changed - Refactor tests to Pest by @alexmanase in https://github.com/spatie/laravel-missing-page-redirector/pull/79 - Add PHP 8.2 Support by @patinthehat in https://github.com/spatie/laravel-missing-page-redirector/pull/80 - Laravel 10.x Compatibility by @laravel-shift in https://github.com/spatie/laravel-missing-page-redirector/pull/81 ### New Contributors - @alexmanase made their first contribution in https://github.com/spatie/laravel-missing-page-redirector/pull/79 - @patinthehat made their first contribution in https://github.com/spatie/laravel-missing-page-redirector/pull/80 **Full Changelog**: https://github.com/spatie/laravel-missing-page-redirector/compare/2.9.3...2.9.4 ## 2.9.3 - 2022-10-13 ### What's Changed - Use Laravel container on private Router - closes #77 by @rodrigopedra in https://github.com/spatie/laravel-missing-page-redirector/pull/78 ### New Contributors - @rodrigopedra made their first contribution in https://github.com/spatie/laravel-missing-page-redirector/pull/78 **Full Changelog**: https://github.com/spatie/laravel-missing-page-redirector/compare/2.9.2...2.9.3 ## 2.9.2 - 2022-05-13 ## What's Changed - remove Str::of for Laravel 6 compatibility by @chrisGeonet in https://github.com/spatie/laravel-missing-page-redirector/pull/76 ## New Contributors - @chrisGeonet made their first contribution in https://github.com/spatie/laravel-missing-page-redirector/pull/76 **Full Changelog**: https://github.com/spatie/laravel-missing-page-redirector/compare/2.9.1...2.9.2 ## 2.9.1 - 2022-04-21 - use `Str` class instead of `str` helper function **Full Changelog**: https://github.com/spatie/laravel-missing-page-redirector/compare/2.9.0...2.9.1 ## 2.9.0 - 2022-04-21 - Add support for wildcard route parameters that span multiple route segments (`/old/*` -> `/new/{wildcard}`) **Full Changelog**: https://github.com/spatie/laravel-missing-page-redirector/compare/2.8.0...2.9.0 ## 2.7.2 - 2021-04-06 - prep for Octane ## 2.7.1 - 2020-12-04 - add support for PHP 8 ## 2.7.0 - 2020-09-09 - add support for Laravel 8 ## 2.6.0 - 2020-03-03 - add support for Laravel 7 ## 2.5.0 - 2019-09-04 - add support for Laravel 6 ## 2.4.0 - 2019-02-27 - drop support for PHP 7.1 and below - drop support for Laravel 5.7 and below ## 2.3.4 - 2019-02-27 - add support for Laravel 5.8 ## 2.3.3 - 2018-12-29 - fix for PHP 7.3 ## 2.3.2 - 2018-08-27 - Added: Laravel 5.7 compatibility ## 2.3.1 - 2018-08-14 - Fixed: Optional parameters not working as expected (#44) ## 2.3.0 - 2018-05-02 - Added: an event will get fired when a route was not found ## 2.2.0 - 2018-02-08 - Added: Laravel 5.6 compatibility ## 2.1.1 - 2017-10-19 - Added: Response code to `RouteWasHit` event ## 2.1.0 - 2017-09-09 - Added: Allow redirects to be enable on a status code basis ## 2.0.0 - 2017-08-31 - Added: Laravel 5.5 compatibility - Removed: Dropped support for older Laravel versions - Changed: Renamed config file from `laravel-missing-page-redirector` to `missing-page-redirector` - Refactored tests ## 1.3.0 - 2017-06-11 - Added: `RouteWasHit` event ## 1.2.0 - 2017-01-23 - Added: Laravel 5.4 compatibility - Removed: Dropped support for older Laravel versions ## 1.1.0 - 2016-10-27 - Added: Support for determining http status code for a redirect ## 1.0.0 - 2016-10-14 - Initial release ================================================ FILE: LICENSE.md ================================================ The MIT License (MIT) Copyright (c) Spatie bvba Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Redirect missing pages in your Laravel application [![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/laravel-missing-page-redirector.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-missing-page-redirector) [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md) [![run-tests](https://github.com/spatie/laravel-missing-page-redirector/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/laravel-missing-page-redirector/actions/workflows/run-tests.yml) [![Total Downloads](https://img.shields.io/packagist/dt/spatie/laravel-missing-page-redirector.svg?style=flat-square)](https://packagist.org/packages/spatie/laravel-missing-page-redirector) When transitioning from a old site to a new one your URLs may change. If your old site was popular you probably want to retain your SEO worth. One way of doing this is by providing [permanent redirects from your old URLs to your new URLs](https://support.google.com/webmasters/answer/93633?hl=en). This package makes that process very easy. When installed you only need to [add your redirects to the config file](https://github.com/spatie/laravel-missing-page-redirector#usage). Want to use the database as your source of redirects? [No problem](https://github.com/spatie/laravel-missing-page-redirector#creating-your-own-redirector)! ## Support us [](https://spatie.be/github-ad-click/laravel-missing-page-redirector) We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us). We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards). ## Installation You can install the package via composer: ``` bash composer require spatie/laravel-missing-page-redirector ``` The package will automatically register itself. Next, prepend/append the `Spatie\MissingPageRedirector\RedirectsMissingPages` middleware to your global middleware stack: ```php // bootstrap/app.php ->withMiddleware(function (Middleware $middleware) { $middleware->append([ \Spatie\MissingPageRedirector\RedirectsMissingPages::class, ]); }) ``` Finally you must publish the config file: ```php php artisan vendor:publish --provider="Spatie\MissingPageRedirector\MissingPageRedirectorServiceProvider" ``` This is the contents of the published config file: ```php return [ /* * This is the class responsible for providing the URLs which must be redirected. * The only requirement for the redirector is that it needs to implement the * `Spatie\MissingPageRedirector\Redirector\Redirector`-interface */ 'redirector' => \Spatie\MissingPageRedirector\Redirector\ConfigurationRedirector::class, /* * By default the package will only redirect 404s. If you want to redirect on other * response codes, just add them to the array. Leave the array empty to redirect * always no matter what the response code. */ 'redirect_status_codes' => [ \Symfony\Component\HttpFoundation\Response::HTTP_NOT_FOUND ], /* * When using the `ConfigurationRedirector` you can specify the redirects in this array. * You can use Laravel's route parameters here. */ 'redirects' => [ // '/non-existing-page' => '/existing-page', // '/old-blog/{url}' => '/new-blog/{url}', ], ]; ``` ## Usage Creating a redirect is easy. You just have to add an entry to the `redirects` key in the config file. ```php 'redirects' => [ '/non-existing-page' => '/existing-page', ], ``` You may use route parameters like you're used to when using Laravel's routes: ```php 'redirects' => [ '/old-blog/{url}' => '/new-blog/{url}', ], ``` Optional parameters are also... an option: ```php 'redirects' => [ '/old-blog/{url?}' => '/new-blog/{url}', ], ``` Finally, you can use an asterix (`*`) as a wildcard parameter that will match multiple URL segments (see [encoded URL slashes in the Laravel docs](https://laravel.com/docs/master/routing#parameters-encoded-forward-slashes) for more info). This is useful when you want to redirect a URL like `/old-blog/foo/bar/baz` to `/new-blog/foo/bar/baz`. ```php 'redirects' => [ '/old-blog/*' => '/new-blog/{wildcard}', // {wilcard} will be the entire path ], ``` By default the package only redirects if the request has a `404` response code but it's possible to be redirected on any response code. To achieve this you may change the ```redirect_status_codes``` option to an array of response codes or leave it empty if you wish to be redirected no matter what the response code was sent to the URL. You may override this using the following syntax to achieve this: ```php 'redirect_status_codes' => [\Symfony\Component\HttpFoundation\Response::HTTP_NOT_FOUND], ``` It is also possible to optionally specify which http response code is used when performing the redirect. By default the ```301 Moved Permanently``` response code is set. You may override this using the following syntax: ```php 'redirects' => [ 'old-page' => ['/new-page', 302], ], ``` ## Events The package will fire a `RouteWasHit` event when it found a redirect for the route. A `RedirectNotFound` is fired when no redirect was found. ## Creating your own redirector By default this package will use the `Spatie\MissingPageRedirector\Redirector\ConfigurationRedirector` which will get its redirects from the config file. If you want to use another source for your redirects (for example a database) you can create your own redirector. A valid redirector is any class that implements the `Spatie\MissingPageRedirector\Redirector\Redirector`-interface. That interface looks like this: ```php namespace Spatie\MissingPageRedirector\Redirector; use Symfony\Component\HttpFoundation\Request; interface Redirector { public function getRedirectsFor(Request $request): array; } ``` The `getRedirectsFor` method should return an array in which the keys are the old URLs and the values the new URLs. ## If you want to use `Route::fallback` If you do not wish to overwrite the default redirector, or if you already have existing `Route::fallback` logic based on [laravel docs](https://laravel.com/docs/11.x/routing#fallback-routes), you can use this package as follow. In the bottom of your `web.php` file, ```php use Spatie\MissingPageRedirector\MissingPageRouter; //... Your other route Route::fallback(function (Request $request) { $redirectResponse = app(MissingPageRouter::class)->getRedirectFor($request); if ($redirectResponse !== null) { return $redirectResponse; } //... Your other logic }); ``` You can adjust the priority of redirect base on your needs. ## Changelog Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. ## Testing ``` bash $ composer test ``` ## Contributing Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details. ## Security If you've found a bug regarding security please mail [security@spatie.be](mailto:security@spatie.be) instead of using the issue tracker. ## Credits - [Freek Van der Herten](https://github.com/freekmurze) - [All Contributors](../../contributors) ## License The MIT License (MIT). Please see [License File](LICENSE.md) for more information. ================================================ FILE: composer.json ================================================ { "name": "spatie/laravel-missing-page-redirector", "description": "Redirect missing pages in your Laravel application", "keywords": [ "spatie", "laravel-missing-page-redirector" ], "homepage": "https://github.com/spatie/laravel-missing-page-redirector", "license": "MIT", "authors": [ { "name": "Freek Van der Herten", "email": "freek@spatie.be", "homepage": "https://spatie.be", "role": "Developer" } ], "require": { "php": "^8.0|^8.1", "laravel/framework": "^8.28|^9.0|^10.0|^11.0|^12.0|^13.0", "spatie/url": "^1.0|^2.0" }, "require-dev": { "orchestra/testbench": "^6.0|^7.0|^8.0|^9.0|^10.0|^11.0", "pestphp/pest": "^1.22|^2.34|^3.7|^4.0", "phpunit/phpunit": "^9.0|^9.3|^10.5|^11.5.3|^12.5.12" }, "autoload": { "psr-4": { "Spatie\\MissingPageRedirector\\": "src" } }, "autoload-dev": { "psr-4": { "Spatie\\MissingPageRedirector\\Test\\": "tests" } }, "scripts": { "test": "vendor/bin/pest" }, "config": { "sort-packages": true, "allow-plugins": { "pestphp/pest-plugin": true } }, "extra": { "laravel": { "providers": [ "Spatie\\MissingPageRedirector\\MissingPageRedirectorServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true } ================================================ FILE: config/missing-page-redirector.php ================================================ \Spatie\MissingPageRedirector\Redirector\ConfigurationRedirector::class, /* * By default the package will only redirect 404s. If you want to redirect on other * response codes, just add them to the array. Leave the array empty to redirect * always no matter what the response code. */ 'redirect_status_codes' => [ \Symfony\Component\HttpFoundation\Response::HTTP_NOT_FOUND, ], /* * When using the `ConfigurationRedirector` you can specify the redirects in this array. * You can use Laravel's route parameters here. */ 'redirects' => [ // '/non-existing-page' => '/existing-page', // '/old-blog/{url}' => '/new-blog/{url}', ], ]; ================================================ FILE: phpunit.xml.dist ================================================ tests src/ ================================================ FILE: src/Events/RedirectNotFound.php ================================================ request = $request; } } ================================================ FILE: src/Events/RouteWasHit.php ================================================ route = $route; $this->missingUrl = $missingUrl; $this->statusCode = $statusCode; } } ================================================ FILE: src/MissingPageRedirectorServiceProvider.php ================================================ publishes([ __DIR__.'/../config/missing-page-redirector.php' => config_path('missing-page-redirector.php'), ], 'config'); $this->app->bind(Redirector::class, config('missing-page-redirector.redirector')); $this->app->bind(MissingPageRouter::class, function ($app) { $router = new Router($app['events'], $app); $redirector = $app->make(Redirector::class); return new MissingPageRouter($router, $redirector); }); } public function register() { $this->mergeConfigFrom(__DIR__.'/../config/missing-page-redirector.php', 'missing-page-redirector'); } } ================================================ FILE: src/MissingPageRouter.php ================================================ router = $router; $this->redirector = $redirector; } /** * @param \Symfony\Component\HttpFoundation\Request $request * * @return \Illuminate\Http\Response|null */ public function getRedirectFor(Request $request) { $redirects = $this->redirector->getRedirectsFor($request); collect($redirects)->each(function ($redirects, $missingUrl) { if (Str::contains($missingUrl, '*')) { $missingUrl = str_replace('*', '{wildcard}', $missingUrl); } $this->router->get($missingUrl, function () use ($redirects, $missingUrl) { $redirectUrl = $this->determineRedirectUrl($redirects); $statusCode = $this->determineRedirectStatusCode($redirects); event(new RouteWasHit($redirectUrl, $missingUrl, $statusCode)); return redirect()->to( $redirectUrl, $statusCode ); })->where('wildcard', '.*'); }); try { return $this->router->dispatch($request); } catch (Exception $e) { event(new RedirectNotFound($request)); return; } } protected function determineRedirectUrl($redirects): string { if (is_array($redirects)) { return $this->resolveRouterParameters($redirects[0]); } return $this->resolveRouterParameters($redirects); } protected function determineRedirectStatusCode($redirects): int { return is_array($redirects) ? $redirects[1] : Response::HTTP_MOVED_PERMANENTLY; } protected function resolveRouterParameters(string $redirectUrl): string { foreach ($this->router->getCurrentRoute()->parameters() as $key => $value) { $redirectUrl = str_replace("{{$key}}", $value, $redirectUrl); } $redirectUrl = preg_replace('/\/{[\w-]+}/', '', $redirectUrl); return $redirectUrl; } } ================================================ FILE: src/Redirector/ConfigurationRedirector.php ================================================ shouldRedirect($response)) { return $response; } $redirectResponse = app(MissingPageRouter::class)->getRedirectFor($request); return $redirectResponse ?? $response; } protected function shouldRedirect($response): bool { $redirectStatusCodes = config('missing-page-redirector.redirect_status_codes'); if (is_null($redirectStatusCodes)) { return false; } if (! count($redirectStatusCodes)) { return true; } return in_array($response->getStatusCode(), $redirectStatusCodes); } } ================================================ FILE: tests/Pest.php ================================================ in('.'); ================================================ FILE: tests/RedirectsMissingPagesTest.php ================================================ get('existing-page') ->assertSee('existing page'); }); it('will redirect a non existing page with a permanent redirect', function () { config()->set('missing-page-redirector.redirects', [ '/non-existing-page' => '/existing-page', ]); $this->get('non-existing-page') ->assertStatus(Response::HTTP_MOVED_PERMANENTLY) ->assertRedirect('/existing-page'); }); it('will redirect wildcard routes', function () { config()->set('missing-page-redirector.redirects', [ '/path/*' => '/new-path/{wildcard}', ]); $this->get('path/to/a/page') ->assertStatus(Response::HTTP_MOVED_PERMANENTLY) ->assertRedirect('/new-path/to/a/page'); }); it('will not redirect an url that is not configured', function () { config()->set('missing-page-redirector.redirects', [ '/non-existing-page' => '/existing-page', ]); $this->get('/not-configured') ->assertStatus(Response::HTTP_NOT_FOUND); }); it('can use named properties', function () { config()->set('missing-page-redirector.redirects', [ '/segment1/{id}/segment2/{slug}' => '/segment2/{slug}', ]); $this->get('/segment1/123/segment2/abc') ->assertRedirect('/segment2/abc'); }); it('can use multiple named parameters in one segment', function () { config()->set('missing-page-redirector.redirects', [ '/new-segment/{id}-{slug}' => '/new-segment/{id}/', ]); $this->get('/new-segment/123-blablabla') ->assertRedirect('/new-segment/123'); }); it('can optionally set the redirect status code', function () { config()->set('missing-page-redirector.redirects', [ '/temporarily-moved' => ['/just-for-now', 302], ]); $this->get('/temporarily-moved') ->assertStatus(302) ->assertRedirect('/just-for-now'); }); it('can use optional parameters', function (string $getRoute, string $redirectRoute) { config()->set('missing-page-redirector.redirects', [ '/old-segment/{parameter1?}/{parameter2?}' => '/new-segment/{parameter1}/{parameter2}', ]); $this->get($getRoute) ->assertRedirect($redirectRoute); })->with([ ['/old-segment', '/new-segment'], ['/old-segment/old-segment2', '/new-segment/old-segment2'], ['/old-segment/old-segment2/old-segment3', '/new-segment/old-segment2/old-segment3'], ]); it('by default it will not redirect requests that are not 404s', function () { $this->get('/response-code/500') ->assertStatus(500); }); it('will fire an event when a route is hit', function () { Event::fake(); config()->set('missing-page-redirector.redirects', [ '/old-segment/{parameter1?}/{parameter2?}' => '/new-segment/', ]); $this->get('/old-segment'); Event::assertDispatched(RouteWasHit::class); }); it('will redirect depending on redirect status code defined', function () { config()->set('missing-page-redirector.redirect_status_codes', [418, 500]); config()->set('missing-page-redirector.redirects', [ '/response-code/500' => '/existing-page', ]); $this->get('/response-code/500') ->assertRedirect('/existing-page'); }); it('will not redirect if the status code is not specified in the config file', function () { config()->set('missing-page-redirector.redirect_status_codes', [418, 403]); config()->set('missing-page-redirector.redirects', [ '/response-code/500' => '/existing-page', ]); $this->get('/response-code/500') ->assertStatus(500); }); it('will redirect on any status code', function () { config()->set('missing-page-redirector.redirect_status_codes', []); config()->set('missing-page-redirector.redirects', [ '/response-code/418' => '/existing-page', ]); $this->get('/response-code/418') ->assertRedirect('/existing-page'); }); it('will fire an event when no redirect was found', function () { Event::fake(); $this->get('/response-code/404'); Event::assertDispatched(RedirectNotFound::class); }); ================================================ FILE: tests/TestCase.php ================================================ setUpRoutes($this->app); } /** * @param \Illuminate\Foundation\Application $app * * @return array */ protected function getPackageProviders($app) { return [ MissingPageRedirectorServiceProvider::class, ]; } /** * @param \Illuminate\Foundation\Application $app */ protected function getEnvironmentSetUp($app) { $app['config']->set('app.key', '6rE9Nz59bGRbeMATftriyQjrpF7DcOQm'); $app['config']->set('app.debug', true); $app->make(Kernel::class)->pushMiddleware(RedirectsMissingPages::class); } /** * @param \Illuminate\Foundation\Application $app */ protected function setUpRoutes($app) { Route::get('/existing-page', function () { return 'existing page'; }); Route::get('response-code/{responseCode}', function (int $responseCode) { abort($responseCode); }); } /** * Assert whether the client was redirected to a given URI. * * @param string $uri * @param array $with * @return $this */ public function assertRedirectedTo($uri, $with = []) { PHPUnit::assertInstanceOf('Illuminate\Http\RedirectResponse', $this->response); PHPUnit::assertEquals($this->app['url']->to($uri), $this->response->headers->get('Location')); return $this; } }