我在我的应用程序中使用next.js,出于 SEO 目的,我在 url 内使用区域设置。因此,为了响应www.domain.com我使用服务器端重定向来重定向到具有区域设置的域(例如:www.domain.com/en.)
为了完成任务,我使用 next.js 中间件,基于next.js 文档提供的示例:
import { NextMiddleware, NextRequest, NextResponse } from "next/server";
const PUBLIC_FILE = /\.(.*)$/;
export const middleware: NextMiddleware = (request: NextRequest) => {
const shouldHandleLocale =
!PUBLIC_FILE.test(request.nextUrl.pathname) &&
!request.nextUrl.pathname.includes("/api/") &&
request.nextUrl.locale === "default";
if (shouldHandleLocale) {
const url = request.nextUrl.clone();
url.pathname = `/en${request.nextUrl.pathname}`;
return NextResponse.redirect(url, 308);
}
return undefined;
};
Run Code Online (Sandbox Code Playgroud)
因此,在函数中,我返回308NextResponse.redirect()状态代码,以永久分配重定向类型。(如果您想了解重定向类型,请阅读此处的文档)
它在应用程序上的所有页面上运行良好,除了主页 ( "/") 之外,其中对主域 ( www.domain.com) …