如何在 NextJS 中解决重定向到外部 url 的问题?

Gil*_*ana 7 javascript redirect external next.js

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

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

我很欣赏任何见解。

w. *_*ale 48

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"
Run Code Online (Sandbox Code Playgroud)

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
      },
    ]
  },
};
Run Code Online (Sandbox Code Playgroud)

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

  • 这应该是公认的答案。 (3认同)

小智 12

您可以尝试使用 window.location

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

// pages/redirect

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


Lyu*_*rov 7

Nextjs-redirect库应该做你想做的