我试着在我的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
6条答案
按热度按时间hgb9j2n61#
为了使重定向和重写在NextJ中正常工作,您还需要确保另外一件事:
如果使用
trailingSlash: true
,则源路径必须以斜杠结尾。还需要考虑干扰路由的任何其他插件或配置。
e0bqpujr2#
你可以添加所有你的导入和
const
定义到第一个array
参数,如下所示jckbn6z73#
您使用的是什么NextJS版本?9.5以上支持重定向
ehxuflar4#
对于遇到此问题的任何人,请尝试重新启动服务器。配置文件将重新加载。
bsxbgnwa5#
在我的例子中,我尝试重定向到外部链接,我有
trailingSlash: true
,我用斜杠结束我的源代码路径。它不起作用,因为我使用了
next/link
中的Link
组件我把它改为普通的
a
标签,它工作了。之前:
之后:
您需要禁用eslint规则
@next/next/no-html-link-for-pages
,以便在构建时不会引发错误在next.config.js文件中:
6psbrbz96#
对于任何正在与此问题作斗争的人,这里有一个解决方案
提问者在
next.config.js
中所做的是正确的,它在documentation中声明,因为您将需要重定向密钥来允许传入的流量传递到其他目的地。因此,其源路径的传入流量为
source: "/sales/guest/form"
并且可能使用if条件if met来重定向到主页,因为他们在
next.config.js
,destination: "/"
中有它要完成此操作,您必须转到pages目录中的
Form
页面,并从Form
页面处理此重定向并导入如下重定向
基本上,在
FORM file
内页中,假设目录路径为:/销售/客人/表格