在 NextJS 中自动重定向的正确方法

Posted

技术标签:

【中文标题】在 NextJS 中自动重定向的正确方法【英文标题】:Propery Way to Redirect Automatic in NextJS 【发布时间】:2021-11-01 10:47:19 【问题描述】:

我有一个索引页面,当他进入索引页面时,我想重定向到/orders 页面。这样做的正确和正确方法是什么?我正在使用 NextJS、Apollo Client 和 React。

import  useRouter  from 'next/router'
import withApollo from '../apollo'

const Index = () => 
  const router = useRouter()
  return router.replace('/orders')


export default withApollo(Index)

【问题讨论】:

【参考方案1】:

对于redirect in Nextjs,您需要在next.config.js 中添加一个设置:

您需要在设置中添加一个redirects 键:

module.exports = 
  async redirects() 
    return [
      
        source: '/',
        destination: '/orders',
        permanent: true,
      ,
    ]
  ,

【讨论】:

谢谢。那么索引页面里面有什么? 此设置在服务器端运行,因此您的索引页面根本不会被呈现。您可以随意删除它。 我会删除 index.page 吗? 是的!因为当用户到达index 页面时,您总是希望重定向到/orders,因此不再需要保留该页面。您的索引页将永远不会是 render

以上是关于在 NextJS 中自动重定向的正确方法的主要内容,如果未能解决你的问题,请参考以下文章

在server.js中获取301重定向数据(Express / NextJS)

NextJS 无法在域上禁用重定向

如何在不重新加载页面的情况下将服务器端重定向到其他页面并仍将 URL 保留在 Nextjs 应用程序中?

NexJs 重定向略有延迟

Next JS 静态站点:将特定路由重定向到另一个站点?

在servletfilter中正确的使用重定向