【问题标题】:How to tackle redirect to an external url in NextJS?如何在 NextJS 中处理重定向到外部 url?
【发布时间】:2021-01-28 04:42:04
【问题描述】:

我的next.config.js 文件具有常规的重定向 规则,所有这些都在同一个域中并且一切正常。但在特定情况下,我需要将请求从某个 URL (mydomain.com/abc) 重定向到不同的域。即不同的domain.com

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

感谢任何见解。

【问题讨论】:

  • docs 表示在这些情况下使用window.location 而不是router.push。如果这没有帮助,您需要提供您尝试过的代码,以便我们帮助解决问题。
  • 我在next.config.js 文件中使用了nextjs-redirect 库和一组自定义重定向。
  • next.config.js 现在内置了外部重定向规则(请参阅nextjs.org/docs/api-reference/next.config.js/redirects

标签: javascript redirect next.js external


【解决方案1】:

最新版本的 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)。

【讨论】:

    【解决方案2】:

    Nextjs-redirect 库应该做你想做的事

    【讨论】:

      【解决方案3】:

      您可以尝试使用 window.location

      这是一个在访问页面时将用户重定向到外部 url 的示例

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-27
        • 2016-09-09
        • 2016-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-24
        相关资源
        最近更新 更多