我正在开发一个 Next.js/Django 项目,用户可以从管理面板添加一些重定向逻辑,例如:
[
{ source: "/about", destination: "google.com" },
{ source: "/about1", destination: "google1.com" },
{ source: "/about2", destination: "google2.com" },
]
Web 应用程序应该能够处理这些动态重定向。
As the Nextjs 文档 https://nextjs.org/docs/api-reference/next.config.js/redirects说,我们可以这样做next.config.js
。问题是我们不能有动态数据next.config.js
。此文件中的每次更改都必须重新启动服务器。
在这里,我们需要一个逻辑,在网站加载时使用 API 获取 url,循环遍历它们并侦听每个路由调用以查看它们是否与重定向数据匹配。
我也尝试过其他一些方法,比如尝试使用 useEffect,但这种方法会导致网站先渲染 404 页面,然后重定向到所需的 url,这对于用户体验的观点来说不太好。
您可以使用 Next.js中间件 https://nextjs.org/docs/advanced-features/middleware获取动态redirects
来自 API 的数组,并添加您自己的逻辑来处理重定向。
Unlike redirects
in the next.config.js
Next.js 中间件在构建时运行,在每个传入页面的请求上运行,并且每次都能动态获取重定向。
export async function middleware(req) {
// Fetch redirects array from API
const res = await fetch('https://example.com/api/redirects');
const redirects = await res.json();
/* Assuming the returned `redirects` array would have the following structure:
[
{ source: '/about-us', destination: '/about' },
{ source: '/google', destination: 'https://google.com' }
]
*/
// Find the matching redirect object
const redirect = redirects.find((redirect) => req.nextUrl.pathname === redirect.source);
if (redirect) {
if (redirect.destination.startsWith('http')) {
// Handle external URL redirects
return NextResponse.redirect(new URL(redirect.destination));
}
// Handle internal URL redirects
return NextResponse.redirect(new URL(redirect.destination, req.url));
}
// Continue if no matching redirect is found
return NextResponse.next();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)