NextJS 在 next.config.js 文件中定义后重定向而不重定向 url

Yuv*_*evy 11 node.js reactjs next.js module.exports

我尝试在我的 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'
        }
    }
);
Run Code Online (Sandbox Code Playgroud)

这是如何执行此操作的文档: https ://nextjs.org/docs/api-reference/next.config.js/redirects

Cod*_*nts 11

为了使重定向和重写在 NextJs 中正常工作,您还需要确保一件事:

如果您正在使用,trailingSlash: true那么您的源路径必须以斜杠结尾。

{
    source: '/old/:id/',  // Notice the slash at the end
    destination: '/new/:id',
},
Run Code Online (Sandbox Code Playgroud)

还需要考虑干扰路由的任何其他插件或配置。


mon*_*lIT 5

您可以将所有导入和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
);
Run Code Online (Sandbox Code Playgroud)


Max*_*hke 0

您使用的是哪个 NextJS 版本?9.5 及以上版本支持重定向