Skip to content

国际化 (i18n) 路由

Astro 的国际化 (i18n) 功能允许你调整项目以适应国际受众。此路由 API 可帮助你生成、使用和验证多语言站点生成的 URL。

¥Astro’s internationalization (i18n) features allow you to adapt your project for an international audience. This routing API helps you generate, use, and verify the URLs that your multi-language site produces.

Astro 的 i18n 路由允许你提供多语言内容,并支持配置默认语言、计算相对页面 URL 以及接受访问者浏览器提供的首选语言。你还可以根据每种语言指定后备语言,以便你的访问者始终可以定向到你网站上的现有内容。

¥Astro’s i18n routing allows you to bring your multilingual content with support for configuring a default language, computing relative page URLs, and accepting preferred languages provided by your visitor’s browser. You can also specify fallback languages on a per-language basis so that your visitors can always be directed to existing content on your site.

¥Routing Logic

Astro 使用 中间件 来实现其路由逻辑。此中间件函数放置在 第一名 中,它等待来自任何其他中间件和每个页面路由的每个 Response,然后最终执行其自己的逻辑。

¥Astro uses a middleware to implement its routing logic. This middleware function is placed in the first position where it awaits every Response coming from any additional middleware and each page route before finally executing its own logic.

这意味着首先运行来自你自己的中间件和页面逻辑的操作(例如重定向),渲染你的路由,然后 i18n 中间件执行其自己的操作,例如验证本地化 URL 是否对应于有效路由。

¥This means that operations (e.g. redirects) from your own middleware and your page logic are run first, your routes are rendered, and then the i18n middleware performs its own actions such as verifying that a localized URL corresponds to a valid route.

你还可以选择 除了 Astro 的 i18n 中间件之外或代替 Astro 的 i18n 中间件,添加你自己的 i18n 逻辑,让你更好地控制路由,同时仍然可以访问 astro:i18n 辅助函数。

¥You can also choose to add your own i18n logic in addition to or instead of Astro’s i18n middleware, giving you even more control over your routes while still having access to the astro:i18n helper functions.

¥Configure i18n routing

需要在 i18n 配置对象中指定所有受支持语言的列表 (locales) 和默认语言 (defaultLocale),默认语言必须是 locales 中列出的语言之一。此外,你可以配置更具体的路由和后备行为以匹配你想要的 URL。

¥Both a list of all supported languages (locales) and a default language (defaultLocale), which must be one of the languages listed in locales, need to be specified in an i18n configuration object. Additionally, you can configure more specific routing and fallback behavior to match your desired URLs.

astro.config.mjs
import { defineConfig } from "astro/config"
export default defineConfig({
i18n: {
locales: ["es", "en", "pt-br"],
defaultLocale: "en",
}
})

¥Create localized folders

按语言组织包含本地化内容的内容文件夹。在 src/pages/ 内的任何位置创建单独的 /[locale]/ 文件夹,Astro 的 基于文件的路由 将在相应的 URL 路径创建你的页面。

¥Organize your content folders with localized content by language. Create individual /[locale]/ folders anywhere within src/pages/ and Astro’s file-based routing will create your pages at corresponding URL paths.

你的文件夹名称必须与 locales 中的项目完全匹配。仅当你将 prefixDefaultLocale: true 配置为显示默认语言的本地化 URL 路径(例如 /en/about/)时,才为你的 defaultLocale 包含本地化文件夹。

¥Your folder names must match the items in locales exactly. Include a localized folder for your defaultLocale only if you configure prefixDefaultLocale: true to show a localized URL path for your default language (e.g. /en/about/).

  • Directorysrc
    • Directorypages
      • about.astro
      • index.astro
      • Directoryes
        • about.astro
        • index.astro
      • Directorypt-br
        • about.astro
        • index.astro

¥Create links

配置 i18n 路由后,你现在可以使用 astro:i18n 模块 中提供的辅助函数(例如 getRelativeLocaleUrl())计算站点内页面的链接。这些生成的链接将始终提供正确的本地化路由,并可以帮助你正确使用或检查网站上的 URL。

¥With i18n routing configured, you can now compute links to pages within your site using the helper functions such as getRelativeLocaleUrl() available from the astro:i18n module. These generated links will always provide the correct, localized route and can help you correctly use, or check, URLs on your site.

你仍然可以手动编写链接。

¥You can also still write the links manually.

src/pages/es/index.astro
---
import { getRelativeLocaleUrl } from 'astro:i18n';
// defaultLocale is "es"
const aboutURL = getRelativeLocaleUrl("es", "about");
---
<a href="/get-started/">¡Vamos!</a>
<a href={getRelativeLocaleUrl('es', 'blog')}>Blog</a>
<a href={aboutURL}>Acerca</a>

Astro 内置的基于文件的路由会根据 src/pages/ 中的文件结构自动为你创建 URL 路由。

¥Astro’s built-in file-based routing automatically creates URL routes for you based on your file structure within src/pages/.

当你配置 i18n 路由时,有关此文件结构(以及生成的相应 URL 路径)的信息可供 i18n 辅助函数使用,以便它们可以生成、使用和验证项目中的路由。这些选项中的许多选项可以一起使用,以实现更多的自定义和每种语言的灵活性。

¥When you configure i18n routing, information about this file structure (and the corresponding URL paths generated) is available to the i18n helper functions so they can generate, use, and verify the routes in your project. Many of these options can be used together for even more customization and per-language flexibility.

你甚至可以选择 手动实现你自己的路由逻辑 以获得更大的控制权。

¥You can even choose to implement your own routing logic manually for even greater control.

Added in: astro@3.5.0

此路由选项定义你的默认语言的 URL 是否应使用语言前缀(例如 /en/about/)。

¥This routing option defines whether or not your default language’s URLs should use a language prefix (e.g. /en/about/).

所有非默认支持的语言都将使用本地化前缀(例如 /fr//french/),并且内容文件必须位于适当的文件夹中。此配置选项允许你指定你的默认语言是否也应遵循本地化的 URL 结构。

¥All non-default supported languages will use a localized prefix (e.g. /fr/ or /french/) and content files must be located in appropriate folders. This configuration option allows you to specify whether your default language should also follow a localized URL structure.

此设置还确定你的默认语言的页面文件必须存在的位置(例如 src/pages/about/src/pages/en/about),因为文件结构和 URL 结构必须与所有语言匹配。

¥This setting also determines where the page files for your default language must exist (e.g. src/pages/about/ or src/pages/en/about) as the file structure and URL structure must match for all languages.

  • "prefixDefaultLocale: false"(默认):默认语言的 URL 将不带 /[locale]/ 前缀。所有其他语言环境都会。

  • "prefixDefaultLocale: true":所有 URL(包括你的默认语言)都将具有 /[locale]/ 前缀。

prefixDefaultLocale: false

标题部分 prefixDefaultLocale: false
astro.config.mjs
import { defineConfig } from "astro/config"
export default defineConfig({
i18n: {
locales: ["es", "en", "fr"],
defaultLocale: "en",
routing: {
prefixDefaultLocale: false
}
}
})

这是默认值。当默认语言的 URL 没有 /[locale]/ 前缀并且默认语言的文件存在于 src/pages/ 的根目录中时,请设置此选项:

¥This is the default value. Set this option when URLs in your default language will not have a /[locale]/ prefix and files in your default language exist at the root of src/pages/:

  • Directorysrc
    • Directorypages
      • about.astro
      • index.astro
      • Directoryes
        • about.astro
        • index.astro
      • Directoryfr
        • about.astro
        • index.astro
  • src/pages/about.astro 将生成路由 example.com/about/

  • src/pages/fr/about.astro 将生成路由 example.com/fr/about/

astro.config.mjs
import { defineConfig } from "astro/config"
export default defineConfig({
i18n: {
locales: ["es", "en", "fr"],
defaultLocale: "en",
routing: {
prefixDefaultLocale: true
}
}
})

当所有路由的 URL 中都包含 /locale/ 前缀并且所有页面内容文件(包括 defaultLocale 的页面内容文件)都存在于本地化文件夹中时,请设置此选项:

¥Set this option when all routes will have their /locale/ prefix in their URL and when all page content files, including those for your defaultLocale, exist in a localized folder:

  • Directorysrc
    • Directorypages
      • index.astro // Note: this file is always required
      • Directoryen
        • index.astro
        • about.astro
      • Directoryes
        • about.astro
        • index.astro
      • Directorypt-br
        • about.astro
        • index.astro
  • 没有语言环境前缀的 URL(例如 example.com/about/)将返回 404(未找到)状态代码,除非你指定 后备策略

Added in: astro@4.2.0

配置 src/pages/index.astro 生成的主 URL (/) 是否重定向到 /<defaultLocale>

¥Configures whether or not the home URL (/) generated by src/pages/index.astro will redirect to /<defaultLocale>.

设置 prefixDefaultLocale: true 还将自动在 routing 配置对象中设置 redirectToDefaultLocale: true。默认情况下,所需的 src/pages/index.astro 文件将自动重定向到默认语言环境的索引页。

¥Setting prefixDefaultLocale: true will also automatically set redirectToDefaultLocale: true in your routing config object. By default, the required src/pages/index.astro file will automatically redirect to the index page of your default locale.

你可以通过 设置 redirectToDefaultLocale: false 选择退出此行为。这允许你拥有一个存在于配置的语言环境文件夹结构之外的站点主页。

¥You can opt out of this behavior by setting redirectToDefaultLocale: false. This allows you to have a site home page that exists outside of your configured locale folder structure.

Added in: astro@4.6.0

启用此选项后,Astro 将禁用其 i18n 中间件,以便你可以实现自己的自定义逻辑。不能使用 routing: "manual" 配置其他 routing 选项(例如 prefixDefaultLocale)。

¥When this option is enabled, Astro will disable its i18n middleware so that you can implement your own custom logic. No other routing options (e.g. prefixDefaultLocale) may be configured with routing: "manual".

你将负责编写自己的路由逻辑,或与你自己的路由逻辑一起编写 手动执行 Astro 的 i18n 中间件

¥You will be responsible for writing your own routing logic, or executing Astro’s i18n middleware manually alongside your own.

astro.config.mjs
import { defineConfig } from "astro/config"
export default defineConfig({
i18n: {
locales: ["es", "en", "fr"],
defaultLocale: "en",
routing: "manual"
}
})

Astro 为你的中间件提供了辅助函数,以便你可以控制自己的默认路由、异常、回退行为、错误捕获等:redirectToDefaultLocale()notFound()redirectToFallback()

¥Astro provides helper functions for your middleware so you can control your own default routing, exceptions, fallback behavior, error catching, etc: redirectToDefaultLocale(), notFound(), and redirectToFallback():

src/middleware.js
import { defineMiddleware } from "astro:middleware";
import { redirectToDefaultLocale } from "astro:i18n"; // function available with `manual` routing
export const onRequest = defineMiddleware(async (ctx, next) => {
if (ctx.url.startsWith("/about")) {
return next();
} else {
return redirectToDefaultLocale(302);
}
})

¥middleware function

middleware 函数手动创建 Astro 的 i18n 中间件。这允许你扩展 Astro 的 i18n 路由,而不是完全替换它。

¥The middleware function manually creates Astro’s i18n middleware. This allows you to extend Astro’s i18n routing instead of completely replacing it.

你可以将 middleware路由选项 结合你自己的中间件运行,使用 sequence 实用程序确定顺序:

¥You can run middleware with routing options in combination with your own middleware, using the sequence utility to determine the order:

src/middleware.js
import {defineMiddleware, sequence} from "astro:middleware";
import { middleware } from "astro:i18n"; // Astro's own i18n routing config
export const userMiddleware = defineMiddleware(async (ctx, next) => {
// this response might come from Astro's i18n middleware, and it might return a 404
const response = await next();
// the /about page is an exception and we want to render it
if (ctx.url.startsWith("/about")) {
return new Response("About page", {
status: 200
});
} else {
return response;
}
});
export const onRequest = sequence(
userMiddleware,
middleware({
redirectToDefaultLocale: false,
prefixDefaultLocale: true
})
)

Added in: astro@4.9.0

此路由选项允许你使用配置了 site@astrojs/node@astrojs/vercel 适配器针对每种语言自定义 server 渲染项目的域。

¥This routing option allows you to customize your domains on a per-language basis for server rendered projects using the @astrojs/node or @astrojs/vercel adapter with a site configured.

添加 i18n.domains 以将你支持的任何 locales 映射到自定义 URL:

¥Add i18n.domains to map any of your supported locales to custom URLs:

astro.config.mjs
import { defineConfig } from "astro/config"
export default defineConfig({
site: "https://example.com",
output: "server", // required, with no prerendered pages
adapter: node({
mode: 'standalone',
}),
i18n: {
locales: ["es", "en", "fr", "ja"],
defaultLocale: "en",
routing: {
prefixDefaultLocale: false
},
domains: {
fr: "https://fr.example.com",
es: "https://example.es"
}
}
})

所有未映射的 locales 将遵循你的 prefixDefaultLocales 配置。但是,即使此值为 falsedefaultLocale 的页面文件也必须存在于本地化文件夹中。对于上述配置,需要一个 /en/ 文件夹。

¥All non-mapped locales will follow your prefixDefaultLocales configuration. However, even if this value is false, page files for your defaultLocale must also exist within a localized folder. For the configuration above, an /en/ folder is required.

使用上述配置:

¥With the above configuration:

  • 文件 /fr/about.astro 将创建 URL https://fr.example.com/about

  • 文件 /es/about.astro 将创建 URL https://example.es/about

  • 文件 /ja/about.astro 将创建 URL https://example.com/ja/about

  • 文件 /en/about.astro 将创建 URL https://example.com/about

上述 URL 也将由 getAbsoluteLocaleUrl()getAbsoluteLocaleUrlList() 函数返回。

¥The above URLs will also be returned by the getAbsoluteLocaleUrl() and getAbsoluteLocaleUrlList() functions.

¥Fallback

当一种语言的页面不存在时(例如尚未翻译的页面),你可以选择根据每种语言显示来自另一个 locale 的后备内容,而不是显示 404 页面。当你还没有每个路由的页面,但你仍想向访问者提供一些内容时,这非常有用。

¥When a page in one language doesn’t exist (e.g. a page that is not yet translated), instead of displaying a 404 page, you can choose to display fallback content from another locale on a per-language basis. This is useful when you do not yet have a page for every route, but you want to still provide some content to your visitors.

你的后备策略由两部分组成:选择哪些语言应该回退到其他语言(i18n.fallback)并选择是否执行 redirectrewrite 来显示回退内容(在 Astro v4.15.0 中添加了 i18n.routing.fallbackType)。

¥Your fallback strategy consists of two parts: choosing which languages should fallback to which other languages (i18n.fallback) and choosing whether to perform a redirect or a rewrite to show the fallback content (i18n.routing.fallbackType added in Astro v4.15.0).

例如,当你配置 i18n.fallback: { fr: "es" } 时,Astro 将确保在 src/pages/fr/ 中为 src/pages/es/ 中存在的每个页面构建一个页面。

¥For example, when you configure i18n.fallback: { fr: "es" }, Astro will ensure that a page is built in src/pages/fr/ for every page that exists in src/pages/es/.

如果任何页面尚不存在,则将根据你的 fallbackType 创建页面:

¥If any page does not already exist, then a page will be created depending on your fallbackType:

  • 重定向到相应的 es 路由(默认行为)。

  • 使用 /es/ 页面(i18n.routing.fallbackType: "rewrite")的内容。

例如,以下配置将 es 设置为任何缺失 fr 路由的后备区域设置。这意味着访问 example.com/fr/my-page/ 的用户将看到 example.com/es/my-page/ 的内容(无需重定向),而不是在 src/pages/fr/my-page.astro 不存在时被带到 404 页面。

¥For example, the configuration below sets es as the fallback locale for any missing fr routes. This means that a user visiting example.com/fr/my-page/ will be shown the content for example.com/es/my-page/ (without being redirected) instead of being taken to a 404 page when src/pages/fr/my-page.astro does not exist.

astro.config.mjs
import { defineConfig } from "astro/config"
export default defineConfig({
i18n: {
locales: ["es", "en", "fr"],
defaultLocale: "en",
fallback: {
fr: "es"
},
routing: {
fallbackType: "rewrite"
}
}
})

自定义区域设置路径

标题部分 自定义区域设置路径

¥Custom locale paths

除了将站点支持的 locales 定义为字符串(例如 “en”、“pt-br”)之外,Astro 还允许你将任意数量的 浏览器识别的语言 codes 映射到自定义 URL path。虽然区域设置可以是任何格式的字符串,只要它们对应于你的项目文件夹结构即可,但 codes 必须遵循浏览器可接受的语法。

¥In addition to defining your site’s supported locales as strings (e.g. “en”, “pt-br”), Astro also allows you to map an arbitrary number of browser-recognized language codes to a custom URL path. While locales can be strings of any format as long as they correspond to your project folder structure, codes must follow the browser’s accepted syntax.

将对象传递到 locales 数组,其中 path 键定义自定义 URL 前缀,codes 指示映射到此 URL 的语言。在这种情况下,你的 /[locale]/ 文件夹名称必须与 path 的值完全匹配,并且你的 URL 将使用 path 值生成。

¥Pass an object to the locales array with a path key to define a custom URL prefix, and codes to indicate the languages mapped to this URL. In this case, your /[locale]/ folder name must match exactly the value of the path and your URLs will be generated using the path value.

如果你支持一种语言的多种变体(例如 "fr""fr-BR""fr-CA")并且你希望将所有这些变体映射到同一个 URL /fr/ 下,甚至完全自定义它(例如 /french/),那么这非常有用:

¥This is useful if you support multiple variations of a language (e.g. "fr", "fr-BR", and "fr-CA") and you want to have all these variations mapped under the same URL /fr/, or even customize it entirely (e.g. /french/):

astro.config.mjs
import { defineConfig } from "astro/config"
export default defineConfig({
i18n: {
locales: ["es", "en", "fr"],
locales: ["es", "en", {
path: "french", // no slashes included
codes: ["fr", "fr-BR", "fr-CA"]
}],
defaultLocale: "en",
routing: {
prefixDefaultLocale: true
}
}
})

当使用 astro:i18n 虚拟模块 中的函数根据你的配置(例如 getRelativeLocaleUrl())计算有效的 URL 路径时,使用 path 作为 locale 的值.

¥When using functions from the astro:i18n virtual module to compute valid URL paths based on your configuration (e.g. getRelativeLocaleUrl()), use the path as the value for locale.

¥Limitations

此功能有一些限制:

¥This feature has some restrictions:

  • site 选项是必需的。

  • output 选项必须设置为 "server"

  • 不能有任何单独的预渲染页面。

Astro 依赖以下标头来支持该功能:

¥Astro relies on the following headers in order to support the feature:

确保你的服务器代理/托管平台能够提供此信息。无法检索这些标题将导致 404(状态代码)页面。

¥Make sure that your server proxy/hosting platform is able to provide this information. Failing to retrieve these headers will result in a 404 (status code) page.

¥Browser language detection

Astro 的 i18n 路由允许你在按需渲染的页面中访问两个用于浏览器语言检测的属性:Astro.preferredLocaleAstro.preferredLocaleList。所有页面(包括静态预渲染页面)都可以访问 Astro.currentLocale

¥Astro’s i18n routing allows you to access two properties for browser language detection in pages rendered on demand: Astro.preferredLocale and Astro.preferredLocaleList. All pages, including static prerendered pages, have access to Astro.currentLocale.

它们结合了浏览器的 Accept-Language 标头和你的 locales(字符串或 codes),以自动尊重访问者的首选语言。

¥These combine the browser’s Accept-Language header, and your locales (strings or codes) to automatically respect your visitor’s preferred languages.

  • Astro.preferredLocale:如果访问者浏览器的首选语言环境包含在你的 locales 数组中,Astro 可以为你的访问者计算首选语言环境。如果不存在此类匹配,则该值未定义。

  • Astro.preferredLocaleList:浏览器请求且网站支持的所有区域设置的数组。这会生成你的网站和访问者之间所有兼容语言的列表。如果在 locales 数组中找不到浏览器请求的语言,则该值为 []。如果浏览器没有指定任何首选语言,则该值为 i18n.locales

  • Astro.currentLocale:使用 locales 配置中指定的语法从当前 URL 计算出的区域设置。如果 URL 不包含 /[locale]/ 前缀,则该值将默认为 i18n.defaultLocale

为了成功匹配访问者的偏好,请使用相同的模式 由浏览器使用 提供你的 codes

¥In order to successfully match your visitors’ preferences, provide your codes using the same pattern used by the browser.

Astro 中文网 - 粤ICP备13048890号