Capítulo 416 de 456
Maps an incoming request path to a different destination path while masking the URL shown to the user (unlike redirects, which change the visible URL). Configured via the rewrites key in next.config.js, applies to client-side routing too.
{ beforeFiles, afterFiles, fallback } (since v10.1) gives fine-grained control over ordering.beforeFiles are checked before filesystem, even after a match.getStaticPaths uses fallback: true/'blocking'.destination are auto-passed as query; if any param IS used in destination, none are auto-passed (must add manually, e.g. /:first?second=:second).destination can point to a full external URL, useful for incremental adoption of Next.js in front of a legacy site.module.exports = {
rewrites() {
return {
beforeFiles: [
{ source: '/some-page', destination: '/somewhere-else', has: [{ type: 'query', key: 'overrideMe' }] },
],
afterFiles: [
{ source: '/non-existent', destination: '/somewhere-else' },
],
fallback: [
{ source: '/:path*', destination: `https://my-old-site.com/:path*` },
],
}
},
}
module.exports = {
rewrites() {
return {
fallback: [
{ source: '/:path*', destination: `https://custom-routes-proxying-endpoint.vercel.app/:path*` },
],
}
},
}
fallback proxiar tudo que ainda não tem rota no Next.js pro site antigo.Ordem de checagem de rotas: 1) headers, 2) redirects, 3) beforeFiles rewrites, 4) arquivos estáticos (public, _next/static, páginas não-dinâmicas), 5) afterFiles rewrites, 6) rotas dinâmicas, 7) fallback rewrites (antes do 404).
| Version | Changes |
|---|---|
| v13.3.0 | missing added |
| v10.2.0 | has added |
| v9.5.0 | Headers added |
trailingSlash: true sem ajustar source: precisa incluir a barra final no source (e no destination se o servidor de destino também exigir).beforeFiles parar no primeiro match: todos os beforeFiles continuam sendo checados até o fim antes de ir pro filesystem.beforeFiles/afterFiles/fallback dão controle preciso sobre onde a rewrite entra na cadeia de resolução de rota.fallback é o padrão certo para "strangler fig" migration de um site legado para Next.js incremental.fallback rewrite (mutuamente exclusivos em certos casos).