Skip to content

Redirects

Greg Bowler edited this page Apr 14, 2026 · 1 revision

Redirects provides an iterator over redirect rules stored in CSV format.

It is designed so we can keep straightforward URL migrations in a file rather than hard-coding them into router callbacks.

CSV format

Each row contains:

  1. the old URI
  2. the new URI

Example:

/about-us,/about
/product/1234,/product/widget-1234
/dir/nested/old-link,/other-dir/new-link,303

Loading redirects

We can construct the object with either a pathname or an SplFileObject:

use GT\Routing\Redirects;

$redirects = new Redirects("redirects.csv");

Applying redirects

BaseRouter::handleRedirects() checks the current request path against the redirect list and throws the appropriate HTTP redirect exception when it finds a match.

$router->handleRedirects($redirects, $request);

In practice we would usually do this before calling route().

The comparison is against the request path, so these rules should be written as path-to-path redirects rather than full URI strings with query components.

Redirect response code

The redirect status comes from RouterConfig::$redirectResponseCode.

Supported mappings are:

  • 300 => HttpMultipleChoices
  • 301 => HttpMovedPermanently
  • 302 => HttpFound
  • 303 => HttpSeeOther
  • 304 => HttpNotModified
  • 307 => HttpTemporaryRedirect
  • any other configured value => HttpPermanentRedirect (308)

Iterating manually

Redirects implements Iterator, so we can inspect or transform the data before applying it:

foreach($redirects as $from => $to) {
	echo "$from -> $to", PHP_EOL;
}

To increase simplicity of application routes, logic can be stored in path-mapped files rather than namespaced classes. Read about this in the logic stream wrapper section.

Clone this wiki locally