簡體   English   中英

如何強制 Next.js 始終重定向到首選用戶語言?

[英]How to force Next.js to always redirect to a preferred user language?

目前,Next.js 僅從根目錄重定向到用戶的語言,因此“/”變為“/fr-FR”。 但是如果用戶訪問例如“/profile”路由,它不會將他重定向到“/fr-FR/profile”。

有沒有辦法強制 Next 進行這些類型的重定向?

從官方 NextJS 文檔中查看此頁面:

為默認語言環境添加前綴

它通過將 domain.com/example 重定向到 domain.com/en/example 來解決您的問題

您可以使用中間件NEXT_LOCALE cookie 來完成,當您更改語言時,您應該設置此 cookie

document.cookie = `NEXT_LOCALE=${langugage};path=/`;

中間件.js

import { NextResponse } from "next/server";

export function middleware(request) {
  const localeCookie = request.cookies.get("NEXT_LOCALE");
  if (localeCookie !== undefined && request.nextUrl.locale !== localeCookie) {
    return NextResponse.redirect(new URL(`/${localeCookie}${request.nextUrl.pathname}`, request.url));
  }
}
export const config = { 
  matcher: ["/", "/about"], // paths on which middleware will work
};

https://nextjs.org/docs/advanced-features/i18n-routing#leveraging-the-next_locale-cookie

https://nextjs.org/docs/advanced-features/i18n-routing#prefixing-the-default-locale

https://nextjs.org/docs/advanced-features/middleware

https://nextjs.org/docs/messages/middleware-upgrade-guide

https://nextjs.org/docs/api-reference/next/server

Sub-path Routing
Sub-path Routing puts the locale in the url path.

With the above configuration en-US, fr, and nl-NL will be available to be routed to, and en-US is the default locale. If you have a pages/blog.js the following urls would be available:

//next.config.js
module.exports = {
  i18n: {
    locales: ['en-US', 'fr', 'nl-NL'],
    defaultLocale: 'en-US',
  },
}

/blog
/fr/blog
/nl-nl/blog
The default locale does not have a prefix.

from Nextjs docs

默認情況下,Next.js 根據頁面請求中發送的Accept-Language header 自動檢測用戶的首選語言環境。

要從此 header 覆蓋區域設置,您可以使用NEXT_LOCALE cookie

可以使用語言切換器設置此 cookie,然后當用戶返回站點時,它將利用 cookie 中指定的語言環境從/重定向到正確的語言環境位置。

在您的情況下,即使用戶在其Accept-Language en中使用語言環境但設置了NEXT_LOCALE=fr-FR cookie,那么在訪問/profile時,用戶將被重定向到/fr-FR/profile直到 cookie刪除或過期。


檢查在 cookie/localSession 中存儲選定的語言選項以獲取有關如何存儲NEXT_LOCALE cookie 的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM