'How to make 301 redirect in NextJS Vercel project?
How can I make 301 re directions from one url to another in NextJS application that is stored on Vercel?
I tried to add custom express server using server.js file but the re directions works only locally and then I read this at vercel: "A custom server can not be deployed on Vercel, the platform Next.js was made for." https://nextjs.org/docs/advanced-features/custom-server
Is there any way to make 301 re directions and still host my app on Vercel?
Solution 1:[1]
Yes you can configure redirects within Vercel (while keeping the project hosted on Vercel). You just have to use a vercel.json file in the root of your directory. The format of the redirect is like this:
// vercel.json
{
"source": "/when-user-hits-this-path",
"destination": "/redirect-them-to-this-path"
}
There's more information on specifics in the vercel docs: https://vercel.com/docs/configuration#project/redirects
Good luck!
- Jake
Solution 2:[2]
If you're hosting on Vercel with NextJS and have a next.config.js
and not a vercel.json
you can do the following;
Edit next.config.js
:
const moduleExports = {
async rewrites() {
return [
{
source: '/foo',
destination: '/bar'
}
]
}
};
module.exports = moduleExports;
Why does this work?: https://nextjs.org/docs/api-reference/next.config.js/redirects
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | jacobedawson |
Solution 2 | zivc |