Alpha ZealPHP is early-stage and under active development. APIs may change between minor versions until v1.0. Feedback and bug reports welcome on GitHub.
API Index — Namespaces, Packages, Reports, Indices

RedirectMiddleware
in package
implements MiddlewareInterface

Redirect Middleware — declarative URL redirects, Apache mod_alias parity.

Two rule shapes, matched in order; the first match short-circuits with a redirect response (the route handler never runs):

  • Prefix (Apache Redirect /old /new): matches the path exactly or as a /old/... prefix; the remainder after the prefix is appended to the target — /old/x → /new/x.
  • Regex (Apache RedirectMatch ^/old/(.*) /new/$1): PCRE pattern with $n backreferences in the target.

The request query string is preserved (appended to the target when the target doesn't carry its own), matching mod_alias.

Usage in app.php:

$app->addMiddleware(new \ZealPHP\Middleware\RedirectMiddleware([
    ['from' => '/old', 'to' => '/new', 'status' => 301],
    ['match' => '#^/blog/(\d+)$#', 'to' => '/posts/$1', 'status' => 302],
]));

Table of Contents

Interfaces

MiddlewareInterface

Properties

$rules  : array<int, array{prefix: ?string, regex: ?string, to: string, status: int}>

Methods

__construct()  : mixed
process()  : ResponseInterface
resolve()  : string|null
targetStaysWhereTheRulePoints()  : bool
A target built from request input must not leave the place the rule's to points: no control characters, no protocol-relative //host (or /\host) unless to itself is protocol-relative, and when to names a fixed host, the result keeps that host (https://new.example + @evil.com is a redirect to evil.com).

Properties

$rules

private array<int, array{prefix: ?string, regex: ?string, to: string, status: int}> $rules = []

Methods

__construct()

public __construct(array<int, array<string, mixed>> $rules) : mixed
Parameters
$rules : array<int, array<string, mixed>>

Each rule needs a to plus either from (prefix) or match (regex); optional status (default 302).

process()

public process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
Parameters
$request : ServerRequestInterface
$handler : RequestHandlerInterface
Return values
ResponseInterface

resolve()

private resolve(array{prefix: ?string, regex: ?string, to: string, status: int} $rule, string $path) : string|null
Parameters
$rule : array{prefix: ?string, regex: ?string, to: string, status: int}
$path : string
Return values
string|null

targetStaysWhereTheRulePoints()

A target built from request input must not leave the place the rule's to points: no control characters, no protocol-relative //host (or /\host) unless to itself is protocol-relative, and when to names a fixed host, the result keeps that host (https://new.example + @evil.com is a redirect to evil.com).

private static targetStaysWhereTheRulePoints(string $to, string $target) : bool
Parameters
$to : string
$target : string
Return values
bool
On this page