如何使用 next.config.js 重定向到与模式匹配的所有路由

Sol*_*tos 5 javascript redirect reactjs next.js

鉴于业务定义:

  • 有些人的名字(名字+姓氏)以 PascalCase 书写,例如“JohnDoe”和“AnalyseKitting”
  • 有“主页”、“个人资料”、“关于”、“常见问题解答”等页面...

鉴于业务需求:

  • 当用户输入“www.ourpage.com/JohnDoe”时,它会重定向到“www.ourpage.com/profile/JohnDoe”
  • 当用户输入“www.ourpage.com/home”时,没有重定向

我的期望是什么

// next.config.js
module.exports = {
  ...
  async redirects() {
    return [
      {
        source: "/:personName((?:[A-Z][a-z]+){2})",
        destination: "/profile/:personName",
        permanent: true
      }
    ]
Run Code Online (Sandbox Code Playgroud)

此代码应仅匹配 PascalCase,并且/profile/:personName仅在存在肯定匹配时才重定向到。

它不起作用,因为写入时/about它被重定向到/profile/about. 这里有一个 SSCCE 沙箱https://codesandbox.io/s/redirects-not-working-as-expected-6z909

什么部分有效但不可维护

对不是来自 Nextjs 或我们的页面列表的任何内容进行负向前瞻。但 PascalCase 命名尚未实现

// next.config.js
module.exports = {
  ...
  async redirects() {
    return [
      {
        source: "/:personName((?!_next|about|profile).+)", // not maintainable
        destination: "/profile/:personName",
        permanent: true
      }
    ]
Run Code Online (Sandbox Code Playgroud)

这是一个SSCCE工作示例codesandbox https://codesandbox.io/s/redirects-working-with-negative-lookahead-bi9xf?file=/next.config.js

可行的解决方法,但不是redirects()

可以通过拦截名为或 的getServerSideProps页面的所有请求来拦截服务器的功能,如下例所示[anyName].js[...anyName].js

// [...root].js
const personNameRegexp = /^(?:[A-Z][a-z]+){2}$/;
export const getServerSideProps = async ({ params }) => {
  const isPersonName = personNameRegexp.test(params.root);
  if (isPersonName) {
    return {
      redirect: {
        destination: `profile/${params.root}`,
        permanent: false
      }
    };
  }

  return {
    props: {}
  };
};
Run Code Online (Sandbox Code Playgroud)

这是一个 SSCCE 工作示例codesandbox https://codesandbox.io/s/redirections-based-on-regex-cmn6c

尝试过其他解决方法但没有运气

我尝试使用这些has对象,但personName显然不是查询参数,并且不能像这样匹配:

        has: [
          {
            type: "query",
            key: "personName",
            value: "(?:[A-Z][a-z]+){2}",
          },
        ],
Run Code Online (Sandbox Code Playgroud)

有什么方法可以在next.config.jssredirects()函数中实现这一点吗?