Deviopath › Next.js

next.config Redirects with Params

Medium · Proxy

next.config.ts can define redirects that run before any page:

``ts async redirects() { return [{ source: "/old-blog/:slug", destination: "/blog/:slug", permanent: true }]; } ``

Params matched in source can be used in destination. permanent: true answers **308**, permanent: false answers **307** (unlike 301/302, these keep the request method). The query string of the request is passed through to the destination.

Write applyRedirects(redirects, url) where url is a path with an optional query string:

- Rules are checked in order and the **first** match wins. Return null if none matches.

- source segments: static text (exact), :name (exactly one segment) or :name* as the last segment (zero or more segments, the value is the matched segments joined with /).

- In destination, replace every :name / :name* segment with its value. If a :name* matched nothing, drop that segment together with its / (so /docs/:path* becomes /docs). Destinations can be absolute URLs and never contain ?.

- Append the original query string (? + query) if there is one.

- Return { destination, statusCode }.

(Simplified: real redirects also support regex params, has / missing conditions, basePath and locale.)

Next: Detect the Locale