V7

浏览器语言检测

默认情况下,@nuxtjs/i18n 通过检测用户浏览器的语言来尝试将用户重定向到他们首选的语言。这由 detectBrowserLanguage 选项控制:

nuxt.config.ts
i18n: {
  detectBrowserLanguage: {
    useCookie: true,
    cookieKey: 'i18n_redirected',
    redirectOn: 'root',  // 推荐
  }
}
为了更好的 SEO,建议将 redirectOn 设置为 root(这是默认值)。设置后,只有在用户访问网站的根路径(/)时,才会尝试进行语言检测。这允许爬虫访问请求的页面,而不是根据检测到的区域被重定向。这也允许链接到特定区域的页面。

浏览器语言要么在客户端运行时从 navigator 检测,要么从 accept-language HTTP 头部中获取。配置的 locales(或在对象形式中指定时的 locales iso 和/或 code)与浏览器报告的语言(例如 en-US,en;q=0.9,no;q=0.8)匹配。如果没有精确匹配的完整语言,语言代码(- 前的字母)将与配置的语言进行匹配。

为了防止用户每次访问应用时都被重定向,@nuxtjs/i18n 在第一次重定向后设置一个 cookie。您可以通过将 detectBrowserLanguage.cookieKey 选项设置为您想要的名称来更改 cookie 的名称,默认值是 i18n_redirected

nuxt.config.ts
i18n: {
  detectBrowserLanguage: {
    useCookie: true,
    cookieKey: 'my_custom_cookie_name'
  }
}

如果您希望用户每次访问应用时都被重定向到其浏览器的语言,请将 detectBrowserLanguage.useCookie 设置为 false,以禁用 cookie。

nuxt.config.ts
i18n: {
  detectBrowserLanguage: {
    useCookie: false
  }
}

要完全禁用浏览器的语言检测功能,可以将 detectBrowserLanguage 设置为 false

nuxt.config.ts
i18n: {
  detectBrowserLanguage: false
}

要在用户每次访问应用时重定向他们并保留他们选择的语言,请启用 alwaysRedirect:

nuxt.config.ts
i18n: {
  detectBrowserLanguage: {
    useCookie: true,
    alwaysRedirect: true
  }
}

在跨源环境(例如在 iFrame 中)中使用 cookie,您可以将 cookieCrossOrigin 设置为 true。这将把 cookie 设置从 SameSite=Lax 更改为 SameSite=None; Secure

nuxt.config.ts
i18n: {
  detectBrowserLanguage: {
    useCookie: true,
    cookieCrossOrigin: true
  }
}