Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redirects via config file #16355

Open
wants to merge 20 commits into
base: 5.x
Choose a base branch
from
Open

Redirects via config file #16355

wants to merge 20 commits into from

Conversation

timkelty
Copy link
Contributor

@timkelty timkelty commented Dec 23, 2024

Description

Adds configurable redirects via config/redirects.php that are only parsed just before serving a 404, so there isn't any added work for normal route/controller requests.

By default, redirects are 302 (temporary) and match the full request path (Craft::$app->getRequest()->getFullPath()) with leading and trailing slashes removed. Yii's URL rule pattern match replacement can be used in to/from.

Matching logic can be overridden via \craft\web\RedirectRule::match callback. When match is used, to, from, and caseSensitive are ignored.

Also provides a \craft\web\ErrorHandler::EVENT_BEFORE_REDIRECT event, should any plugins want to know about a handled redirect.

<?php

return [
    // Path match (case-insensitive by default)
    'redirect/from' => 'redirect/to',

    // Path match with Yii URL Rule named parameters
    // https://www.yiiframework.com/doc/guide/2.0/en/runtime-routing#named-parameters
    'redirect/from/foo/<bar:{slug}>' => 'redirect/to/<bar>',

    // Path match (case-sensitive)
    [
        'from' => 'redirect/FROM/<year:\d{4}>/<month>',
        'to' => 'https://redirect.to/<year>/<month>',
        'caseSensitive' => true,
    ],

    // Custom match callback
    [
        'match' => function (\Psr\Http\Message\UriInterface $url): ?string {
            parse_str($url->getQuery(), $params);

            return isset($params['bar'])
                ? sprintf('redirect/to/%s', $params['bar'])
                : null;
        },
        'statusCode' => 301,
    ],
];

@timkelty timkelty marked this pull request as ready for review December 23, 2024 15:41
@timkelty timkelty marked this pull request as draft January 7, 2025 22:22
@timkelty timkelty marked this pull request as ready for review January 8, 2025 02:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant