In Next.js, we can list all the redirections inside the next.config.js file.
Assume that the old path is /old-page and the new path is /new-page. Then the redirection code will be coded like below.
adding the attribute permanent: true will make the redirection a status code of 301.
next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-page',
destination: '/new-page',
permanent: true,
},
]
},
}
If you are passing a query to the destination path then
next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-page/:path*',
destination: '/new-page/:path*',
permanent: true,
},
]
},
}
For example when /blog1/post-1?user=test is requested, the user will be redirected to /blog/post-1?user=test.
Path matching
If we have the slug or id or any values, that changes in our URL we can match the paths and redirect from the old path to the new path.
For example, if we have written a redirection code from /old-blog/:slug to /new-blog/:slug, the change in slug will now affect the redirection.
That means, the path /old-blog/post-1 will redirect to the new path /new-blog/post-1.
next.config.js
module.exports = {
async redirects() {
return [
{
source: '/old-blog/:slug',
destination: '/new-blog/:slug',
permanent: true,
},
]
},
}
More redirections such as with i18n support are listed on the official Next.js page. You have to refer it here.