简体   繁体   English

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

[英]How to tackle redirect to an external url in NextJS?

I have in place my next.config.js file with regular redirect rules, all within the same domain and all works fine.我在我的next.config.js文件中设置了常规重定向规则,所有这些都在同一个域中并且一切正常。 But in a specific case, I need to redirect the request from a certain URL (mydomain.com/abc) to a different domain.但在特定情况下,我需要将请求从某个 URL (mydomain.com/abc) 重定向到不同的域。 ie differentdomain.com即不同域.com

How do I go about creating this rule to redirect to an external link in NextJs?如何创建此规则以重定向到 NextJs 中的外部链接?

I appreciate any insight.我很欣赏任何见解。

Nextjs-redirect库应该做你想做的

The latest version of Next.js has this built in using the next.config.js script (see https://nextjs.org/docs/api-reference/next.config.js/redirects ). Next.js 的最新版本使用next.config.js脚本(参见https://nextjs.org/docs/api-reference/next.config.js/redirects )内置了这个。 No need for additional plugins.不需要额外的插件。

To test, copy the NextJs sample app:要进行测试,请复制 NextJs 示例应用程序:

npx create-next-app nextjs-blog --use-npm --example "https://github.com/vercel/next-learn-starter/tree/master/learn-starter"

Add a next.config.js file to the root folder with the following code:使用以下代码将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
      },
    ]
  },
};

When you start the app npm run dev and visit localhost:3000, it should redirect to the destination URL specified in the next.config.js script ( https://stackoverflow.com/posts/66662033 ).当您启动应用程序npm run dev并访问 localhost:3000 时,它应该重定向到 next.config.js 脚本中指定的目标 URL ( https://stackoverflow.com/posts/66662033 )。

You can try using window.location您可以尝试使用 window.location

Here's an example in which upon visiting a page it redirects the user to external url这是一个示例,其中在访问页面时它将用户重定向到外部 url

// pages/redirect

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM