繁体   English   中英

NextJS 动态路由的中间件匹配器

[英]NextJS Middleware Matcher For Dynamic Routes

我正在建立一个带有子域的网站。 每个子域都使用中间件映射到基于文件的页面。 下面是我如何将子域映射到页面的示例:

  • app.com映射到/home
  • app.com/pricing映射到/home/pricing
  • subdomain1.app.com/dashboard映射到/_subdomains/subdomain1/dashboard
  • subdomain2.app.com/dashboard/home映射到/_subdomains/subdomain2/dashboard/home

app.comsubdomain1.app.comsubdomain1.app.com/dashboard/和其他一切工作正常,但当我尝试访问subdomain1.app.com/dashboard/home我得到 404 Not Found。

这是我的文件夹结构:

pages/
├── _subdomains/
│   └── [subdomain]/
│       ├── dashboard/
│       │   ├── home.tsx
│       │   └── index.tsx
│       └── index.tsx
├── home/
│   └── ...
└── _app.tsx
import { NextRequest, NextResponse } from 'next/server';

export const config = {
  // I have a feeling this isn't matching /_subdomains/subdomain/dashboard/home
  matcher: ['/', '/([^/.]*)', '/auth/([^/.]*)', '/_subdomains/:path*'], 
};

export default async function middleware(req: NextRequest) {
  const url = req.nextUrl;
  const hostname = req.headers.get('host') || process.env.ROOT_DOMAIN;

  if (!hostname) {
    throw Error('Middleware -> No hostname');
  }

  const currentHost = hostname.replace(`.${process.env.ROOT_DOMAIN}`, '');

  if (currentHost === process.env.ROOT_DOMAIN) {
    url.pathname = `/home${url.pathname}`;
  } else {
    console.log(`/_subdomains/${currentHost}${url.pathname}`)
    url.pathname = `/_subdomains/${currentHost}${url.pathname}`;
  }

  return NextResponse.rewrite(url);
}

我相当肯定是匹配器不起作用,但我不知道为什么。

根据文档匹配/_subdomains/:path*应该匹配/_subdomains/a/b/c但在这种情况下它不起作用。 或者这可能是另一个我不确定的问题

通过将匹配器更改为

matcher: [
     /*
      * Match all paths except for:
      * 1. /api routes
      * 2. /_next (Next.js internals)
      * 3. /fonts (inside /public)
      * 4. /examples (inside /public)
      * 5. all root files inside /public (e.g. /favicon.ico)
      */
     "/((?!api|_next|fonts|examples|[\\w-]+\\.\\w+).*)",
   ],

多亏了这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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