next.config Redirects with has and missing
Hard · Config
The redirects() option in next.config.ts returns rules { source, destination, permanent }. They are checked before the filesystem, in order, and the first match wins. permanent: true uses status 308 and false uses 307 (they keep the request method, unlike 301/302); a rule may set statusCode instead.
Write matchRedirect(redirects, request). request is { url, headers?, cookies? } where url is absolute and header names are lowercase. Return { destination, statusCode } or null. This is a simplified model of redirect matching: ignore basePath and locale fields (as if no basePath is configured).
Source patterns, matched against the URL path (without a trailing slash) segment by segment:
- a literal segment must be equal;
- :name matches one segment, :name(regex) one segment that fully matches the regex;
- :name* (zero or more) and :name+ (one or more) take all remaining segments, joined with / (they are always last).
has and missing items are { type, key?, value? } with type "header" (key compared lowercase), "cookie", "query" or "host" (the URL hostname, no port). An item matches when the value exists and is not empty and, if value is given, new RegExp("^" + value + "$") matches it. Named groups in value (like (?<sub>...)) become params; without value, the found value is stored under key (not for host). All has items must match and no missing item may match.
Destination:
- First split the destination at its first ? into a path and a query, then fill both parts separately (so the ? in /promo/:item?from=:ref starts the query).
- Replace each :name (optionally followed by *, + or ?) with its param. A param that captured nothing is removed together with the / just before it (/guide/:path* becomes /guide).
- Query values from the request are passed through: start with the request's query, then set each query param of the destination (replacing an existing key in place, otherwise appending), and serialize with URLSearchParams.