我已经准备好了 next.config.js
文件,并设置了常规的重定向规则,所有规则都在同一个域名内,一切正常。但在特定情况下,我需要将请求从某个URL(mydomain.com/abc)重定向到另一个域名,即不同的域名differentdomain.com。
如何在 NextJs 中创建此规则以重定向到外部链接?
感谢任何见解。
我已经准备好了 next.config.js
文件,并设置了常规的重定向规则,所有规则都在同一个域名内,一切正常。但在特定情况下,我需要将请求从某个URL(mydomain.com/abc)重定向到另一个域名,即不同的域名differentdomain.com。
如何在 NextJs 中创建此规则以重定向到外部链接?
感谢任何见解。
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)。
// pages/redirect
import {useEffect} from 'react'
export default function redirect() {
useEffect(() => {
window.location.assign('https://duckduckgo.com/')
})
return(
<>
</>
)
}
window.location
而不是router.push
。如果这并不能解决问题,您需要提供您尝试的代码,以便我们可以帮助您进行故障排除。 - Ouroborusnext.config.js
文件中使用了nextjs-redirect
库,并设置了一组自定义重定向。 - Gilson Viana