简体   繁体   中英

How to redirect / into basePath in Next.js config?

Every time that user enter into / I want to redirect into basePath that I already set.

Here is my next.config.js

module.exports = {
  basePath: '/docs',
}

So every time I enter path / I want to redirect into /docs .

Here is what I've tried.

module.exports = {
  basePath: '/docs',
  async rewrites() {
    return [
      {
        source: '/',
        destination: '/docs',
      },
    ];
  },
  async redirects() {
    return [
      {
        source: '/',
        destination: '/docs',
      },
    ];
  },
};

The problem is this rewrites and redirects are working with basePath only.

For example

async redirects() {
        return [
          {
            source: '/test',
            destination: '/hello',
          },
        ];
      },

I enter into /docs/test it will redirect into /docs/hello .

But I want / to go to /docs .

exportPathMap allows you to specify a mapping of request paths to page destinations, to be used during export. Paths defined in exportPathMap will also be available when using next dev.

example

 module.exports = { exportPathMap: async function ( defaultPathMap, { dev, dir, outDir, distDir, buildId } ) { return { '/': { page: '/' }, '/about': { page: '/about' }, '/p/hello-nextjs': { page: '/post', query: { title: 'hello-nextjs' } }, '/p/learn-nextjs': { page: '/post', query: { title: 'learn-nextjs' } }, '/p/deploy-nextjs': { page: '/post', query: { title: 'deploy-nextjs' } }, } }, }

You can use basePath: false option to disable the automatic basePath prefixing of source and destination .

module.exports = {
    basePath: '/docs',
    async redirects() {
        return [
            {
                source: '/',
                destination: '/docs',
                basePath: false
            }
        ]
    }
};

This will correctly redirect / path to /docs .

The same applies to rewrites , if you were to use that instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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