多语言网站的 Next.js url 结构

Mar*_*ler 3 next.js

我正在将我的应用程序迁移到 Next.js。目前我的 url 结构如下:

www.example.com/ <-- English
www.example.com/de <-- German
www.example.com/page <-- English
www.example.com/de/page <-- German
Run Code Online (Sandbox Code Playgroud)

所以我的英文网站的网址中没有该语言。如果有人尝试访问网址中包含“en”的网站,他将被转发。

我如何在 Next.js 中实现这一目标?/pages 目录中始终有两个文件(即“[语言].js”和“index.js”)似乎不是正确的解决方案。

nun*_*sta 6

使用 NextJS 10,您可以在本地完成此操作。你的 next.config.js 看起来像这样:

module.exports = {
  i18n: {
    locales: ['en', 'de'],
    defaultLocale: 'en',
  },
}
Run Code Online (Sandbox Code Playgroud)

这是www.example.com/defaultLocale的语言。

然后您可以使用像next-i18next这样的库来存储翻译。


Mar*_*ler 5

从 Next.js 9.4 开始,有一个实验性功能“自定义路由”。这提供了更优雅的解决方案。请参阅此处的讨论:https://github.com/zeit/next.js/issues/9081

用法示例:

// next.config.js
module.exports = {
  async rewrites() {
    return [
      // Basic `path-to-regexp` usage
      // Query object shape: { id: string }
      { source: "/user/:id", destination: "/user_profile" },

      // Optional Language
      // Query object shape: { lang?: string }
      { source: "/:lang(en|es)?/about", destination: "/about" },

      // Advanced rewrite
      // Query object shape: { id: string } (in addition to dynamic route param)
      { source: "/u/:id", destination: "/user/:id" }
    ];
  }
};
Run Code Online (Sandbox Code Playgroud)