Home > Software design >  How to make 301 redirect in Gatsby website hosted on Vercel?
How to make 301 redirect in Gatsby website hosted on Vercel?

Time:09-25

image of vercel.json for reference

I am using gatsby js for my website and hosted it on vercel and now I want to do 301 redirect for my website but i don't want to use gatsby-cloud for this. is their any way i can do it using vercel.

This is the documentation https://vercel.com/docs/cli#project/redirects but I am not able to understand it properly as it is saying to create a vercel.json file, can anyone help me understand it better?

CodePudding user response:

Of course, you don't need Gatsby Cloud to make redirections, you just need server rules.

In the case of Vercel, according to this GitHub thread (and pulling a lof of similar threads), Next doesn't support by default Gatsby redirections of out the box so the only reliable approach is using createRedirect API. Inside your createPages function (if present) add the following:

// Generally you create redirects while creating pages.
exports.createPages = ({ graphql, actions }) => {
  const { createRedirect } = actions
  createRedirect({ fromPath: '/old-url', toPath: '/new-url', isPermanent: true })
  createRedirect({ fromPath: '/url', toPath: '/zn-CH/url', Language: 'zn' })
  createRedirect({ fromPath: '/not_so-pretty_url', toPath: '/pretty/url', statusCode: 200 })
  // Create pages here
}

Next will consume redirects created with this action and creating appropriate "now" routes.

  • Related