Rewrites
Examples
Rewrites allow you to map an incoming request path to a different destination path.
Rewrites are only available on the Node.js environment and do not affect client-side routing.
Rewrites are not able to override public files or routes in the pages directory as these have higher priority than rewrites. For example, if you have you are not able to rewrite /
to another location unless you rename the pages/index.js
file.
rewrites
is an async function that expects an array to be returned holding objects with source
and destination
properties:
source
is the incoming request path pattern.destination
is the path you want to route to.
Path matches are allowed, for example /blog/:slug
will match /blog/hello-world
(no nested paths):
module.exports = {
async rewrites() {
return [
{
source: '/blog/:slug',
},
},
}
To match a wildcard path you can use *
after a parameter, for example /blog/:slug*
will match /blog/a/b/c/d/hello-world
:
To match a regex path you can wrap the regex in parenthesis after a parameter, for example /blog/:slug(\\d{1,})
will match /blog/123
but not /blog/abc
:
module.exports = {
async rewrites() {
return [
{
source: '/old-blog/:post(\\d{1,})',
destination: '/blog/:post', // Matched parameters can be used in the destination
},
]
},
}
Rewriting to an external URL
Rewrites allow you to rewrite to an external url. This is especially useful for incrementally adopting Next.js.
You can also make Next.js check the application routes before falling back to proxying to the previous website.
This way you don’t have to change the rewrites configuration when migrating more pages to Next.js
async rewrites() {
return [
// we need to define a no-op rewrite to trigger checking
// all pages/static files before we attempt proxying
{
source: '/:path*',
destination: '/:path*',
},
{
source: '/:path*',
destination: `https://custom-routes-proxying-endpoint.vercel.app/:path*`,
},
]
}
When leveraging with rewrites each source
and destination
is automatically prefixed with the unless you add basePath: false
to the rewrite: