我试图在NextJS应用程序中定义重定向。但它不起作用。
这就是我在next.config.js文件中尝试的方法:
const withImages = require('next-images')
const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");
module.exports = withPlugins(
[
[optimizedImages, {
inlineImageLimit: 512
}]
],
{
async redirects() {
return [
{
source: "/sales/guest/form",
destination: "/",
permanent: true
}
]
},
env:{
testEnvVar: 'vallll'
}
}
);
这是如何做到这一点的文档:https://nextjs.org/docs/api-reference/next.config.js/redirects
为了在NextJs中正确进行重定向和重写,您还需要确保一件事:
如果使用trailingSlash: true
,则源路径必须以斜线结束。
{
source: '/old/:id/', // Notice the slash at the end
destination: '/new/:id',
},
任何其他干扰路由的插件或配置也需要考虑在内。
您可以将所有导入的内容以及const
定义添加到第一个array
参数中,如
const withPlugins = require('next-compose-plugins');
const css = require('@zeit/next-css');
const less = require('@zeit/next-less');
const nextConfig = {
target: 'serverless',
webpack(config, { isServer, webpack }) {
// al your config
return config;
},
};
const redirects = {
async redirects() {
return [
{
source: '/old/blogs/:slug*',
destination: 'whatever your new rewrite url',
permanent: true,
},
];
},
};
module.exports = withPlugins(
[
[css],
[less],
[redirects], // you can directly drop your redirect rules here
],
nextConfig
);
您使用的NextJS版本是什么?从9.5到支持重定向
对于有此问题的用户,请尝试重新启动服务器。然后将重新加载配置文件。
在我的案例中,我尝试重定向到外部链接。我有trailingSlash: true
,我用斜杠结束了我的源路径。
它不起作用,因为我使用了next/link
中的Link
组件
我把它改为普通的a
标签,它就工作了。
之前:
<Link href="/some-path" passHref>
<a>
to external
</a>
</Link>
之后:
{/* eslint-disable-next-line @next/next/no-html-link-for-pages */}
<a href="/some-path">
to external
</a>
您需要禁用esint规则
@next/next/no-html-link-for-pages
,这样它在构建时就不会引发错误
在next.config.js文件中:
module.exports = {
trailingSlash: true,
reactStrictMode: true,
async redirects() {
return [
{
source: "/some-path",
destination: "https://example.com",
permanent: true,
},
]
},
}
对于任何遇到此问题的人,这里有一个解决方案
提问者在next.config.js
中所做的是正确的,文档中也说明了这一点,因为您需要重定向密钥才能将传入流量传递到其他目的地。
因此,源路径的传入流量是source: "/sales/guest/form"
如果满足条件,则使用if条件重定向到主页,因为它们在next.config.js
、destination: "/"
中有主页
要完成此操作,您必须转到pages目录中的Form
页面,并解决从Form
页面重定向的问题
并像下面的一样导入重定向
因此,基本上在FORM file
内部页面中,假设通过目录的路径如下:
/销售/客人/表格
import { redirect } from 'next/navigation';
const Form = () => {
// prehaps have a condition to tell it when to redirect so:
// this condition is met whatever
if (1 === 1) {
redirect("/");
}
// .. rest of the code
}
export default Form;