如何在NextJS中处理重定向到外部url的问题



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

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

我很欣赏任何见解。

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)。

Nextjs重定向库应该做您想要的

您可以尝试使用window.location

这里有一个例子,当访问一个页面时,它会将用户重定向到外部url

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

最新更新