如何在NextJS中处理重定向到外部URL?

28

我已经准备好了 next.config.js 文件,并设置了常规的重定向规则,所有规则都在同一个域名内,一切正常。但在特定情况下,我需要将请求从某个URL(mydomain.com/abc)重定向到另一个域名,即不同的域名differentdomain.com。

如何在 NextJs 中创建此规则以重定向到外部链接?

感谢任何见解。


5
文档建议在这些情况下使用 window.location 而不是 router.push。如果这并不能解决问题,您需要提供您尝试的代码,以便我们可以帮助您进行故障排除。 - Ouroborus
我在next.config.js文件中使用了nextjs-redirect库,并设置了一组自定义重定向。 - Gilson Viana
2
现在,外部重定向规则已经集成到next.config.js中(请参阅https://nextjs.org/docs/api-reference/next.config.js/redirects)。 - w. Patrick Gale
3个回答

42
最新版本的Next.js使用next.config.js脚本内置了此功能(请参见https://nextjs.org/docs/api-reference/next.config.js/redirects)。无需额外的插件。要进行测试,请复制NextJs示例应用程序:
npx create-next-app nextjs-blog --use-npm --example "https://github.com/vercel/next-learn-starter/tree/master/learn-starter"
在根目录下添加一个名为 next.config.js 的文件,并将以下代码复制到其中:
// this simply tests the redirecting of the root path (source)
module.exports = {
  async redirects() {
    return [
      {
        source: '/',
        destination: 'https://stackoverflow.com/posts/66662033',
        permanent: false,
        basePath: false
      },
    ]
  },
};

当你启动应用程序 npm run dev 并访问 localhost:3000 时,它应该重定向到 next.config.js 脚本中指定的目标 URL(https://stackoverflow.com/posts/66662033)。


3
这应该是被接受的答案。 - J. Adam Connor

10
你可以尝试使用window.location。
以下是一个示例,在其中访问页面时会将用户重定向到外部 URL。
// pages/redirect

import {useEffect} from 'react'
export default function redirect() {
    useEffect(() => {
        window.location.assign('https://duckduckgo.com/')
    })
    return(
        <>
        </>
    )
}

1
问题是,当你返回页面时,它会返回到页面/重定向,并再次重定向到位置。 - Flavio Oliveira
...而更大的问题是它只能在启用JavaScript的情况下工作,并且会被搜索引擎忽略等。 - Bergi

10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接