【问题标题】:How to force Next.js to always redirect to a preferred user language?如何强制 Next.js 始终重定向到首选用户语言?
【发布时间】:2021-08-02 17:17:13
【问题描述】:

目前,Next.js 仅从根目录重定向到用户的语言,因此“/”变为“/fr-FR”。但是如果用户访问例如“/profile”路由,它不会将他重定向到“/fr-FR/profile”。

有没有办法强制 Next 进行这些类型的重定向?

【问题讨论】:

标签: javascript internationalization next.js i18next


【解决方案1】:

默认情况下,Next.js 会根据页面请求中发送的 Accept-Language 标头自动检测用户的首选语言环境。

要从此标头覆盖区域设置,您可以使用NEXT_LOCALE cookie。

可以使用语言切换器设置此 cookie,然后当用户返回站点时,它会在从 / 重定向到正确的语言环境位置时利用 cookie 中指定的语言环境。

在您的情况下,即使用户在其Accept-Language 标头中具有区域设置en,但设置了NEXT_LOCALE=fr-FR cookie,那么当访问/profile 时,用户将被重定向到/fr-FR/profile,直到cookie被删除或过期。


查看Storing selected language option in cookie/localSession 以获取有关如何存储NEXT_LOCALE cookie 的示例。

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

    • 是的,但是如何强制重定向到用户的首选语言?
    猜你喜欢
    • 2012-08-17
    • 1970-01-01
    • 2014-03-20
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-21
    • 2010-11-05
    相关资源
    最近更新 更多