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 11 commits into
base: 5.x
Choose a base branch
from
Open

Redirects via config file #16355

wants to merge 11 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. What is matched can be configured via \craft\web\Redirect::match, which is a callback that takes a \Psr\Http\Message\UriInterface of the URL.

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

Note: for future-proofing, named capture group replacement uses PHP/PCRE's native syntax ((?<name>group)) and NOT Yii's similar but different route syntax ((?<name:group)>).

<?php
// config/redirects.php
return [
    // Exact path match
    'redirect/from' => 'redirect/to',

    // Path match with named capture group
    'redirect/from/(?<year>\d{4})' => [
        'to' => 'redirect/to/{year}',
        'matchType' => 'regex',
        'caseSensitive' => false,
    ],

    // Match path and query string
    new \craft\web\Redirect([
        'from' => 'bar=(?<bar>[^&]+)',
        'to' => '/redirect/to/{bar}',
        'match' => fn(\Psr\Http\Message\UriInterface $url) => (string) "{$url->getPath()}?{$url->getQuery()}",
        'matchType' => \craft\enums\MatchType::Regex,
    ]),

    // Match full URL
    'https://craft-5-project.ddev.site/redirect/from/foo/(.+)' => [
        'to' => 'https://redirect.to/{1}',
        'match' => fn(\Psr\Http\Message\UriInterface $url) => (string) $url,
        'matchType' => \craft\enums\MatchType::Regex,
        'statusCode' => 301,
        'caseSensitive' => false,
    ],
];

@timkelty timkelty marked this pull request as ready for review December 23, 2024 15:41
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