Paraglide JS 基于 Web 标准 URLPattern API,提供强大的基于 URL 的国际化路由。本指南介绍如何配置 URL 模式,以实现语言区域检测、路径名翻译、基于域名的本地化等功能。
i18n 路由为每个语言区域分配独立的 URL,例如英语使用 /about,德语使用 /de/about。这是国际化网站的黄金标准,原因如下:
- SEO:搜索引擎会分别索引每个语言版本
- 便于分享:用户可以分享对应自己语言的链接
[!TIP]本指南侧重于 URL 模式配置。如需了解所有语言区域检测策略(cookie、localStorage、请求头等),请参阅策略文档。
快速开始
在 strategy 数组中添加 url,即可启用基于 URL 的语言区域检测:
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "baseLocale"],
});
就这么简单。默认情况下,Paraglide 会为非基础语言区域添加 /de/about 这样的语言区域前缀,基础语言区域则不加前缀 (/about) 。对于这种常见配置,无需设置 urlPatterns。
有其他需求?可以用 urlPatterns 自定义:
- 翻译路径名 - 英语为
/about,德语为/ueber-uns - 基于域名的路由 - 英语使用
example.com,德语使用de.example.com - 为所有语言区域加前缀 -
/en/about和/de/about(包括基础语言区域) - 混合模式 - 部分路由加前缀,部分不加
继续阅读,了解 URL 模式的工作原理,并查看配置示例。
URLPattern polyfill
当你配置了自定义 urlPatterns 或 routeStrategies 时,Paraglide 会在生成的运行时中包含 URLPattern polyfill。
未使用路由策略的内置默认路由则不会包含它。
在编译器选项或 paraglide.config.js/ts 中设置 lazyUrlPatternPolyfill: true,
即可仅在环境缺少 URLPattern 时才加载该 polyfill:
export default {
lazyUrlPatternPolyfill: true,
// 你的 urlPatterns 或 routeStrategies 配置
};
这需要 Vite 7+,或其他支持 顶层 await 的 ESM 工具链和运行时。生成的运行时会按需 await 导入 polyfill:
if (typeof URLPattern === "undefined") {
await import("@inlang/paraglide-js/urlpattern-polyfill");
}
应用仍可使用普通的静态导入和同步路由调用。ESM
导入方会等待运行时初始化完成,因此应用无需使用 ready promise。
原生支持 URLPattern 的环境会完全跳过动态导入。
打包工具可以生成独立的 polyfill chunk,仅在需要时加载。
该选项默认为 false,即保留静态 polyfill 导入,
以兼容较旧的构建目标。启用后不支持 CommonJS 和 IIFE 输出。
编译器内部的 polyfill 加载方式不受影响。
核心概念
URL 模式的工作原理
每个 URL 模式由两部分组成:
pattern:规范路由结构 (例如"/about"或"/:path(.*)?")localized:一个元组数组,将每个语言区域映射到对应的 URL 形式
{
pattern: "/about", // 规范路由
localized: [
["en", "/about"], // 英语:/about
["de", "/ueber-uns"], // 德语:/ueber-uns
],
}
元组格式为 [locale, localizedPath]。用户访问 /ueber-uns 时,Paraglide 会将其匹配到德语语言区域。调用 localizeHref("/about", { locale: "de" }) 时,会返回 /ueber-uns。
转换示例:
| 访问的 URL | 检测到的语言区域 | 规范路径 |
|---|---|---|
/about | en | /about |
/ueber-uns | de | /about |
/de/produkte/123 | de | /products/123 |
/products/123 | en | /products/123 |
模式匹配顺序
模式按数组顺序依次求值,以第一个匹配项为准。因此,请将具体模式放在通配符之前:
urlPatterns: [
{ pattern: "/blog/:id", localized: [...] }, // 具体模式在前
{ pattern: "/:path(.*)?", localized: [...] }, // 通配符在后
]
[!TIP]可以使用 https://urlpattern.com/ 测试你的 URL 模式。
URL 模式配置
常用模式一览
| 使用场景 | 示例 URL | 模式 |
|---|---|---|
| 仅为非默认语言区域添加前缀 | /about、/de/about | ["de", "/de/:path(.*)?"]、["en", "/:path(.*)?"] |
| 为所有语言区域添加前缀 | /en/about、/de/about | ["en", "/en/:path(.*)?"]、["de", "/de/:path(.*)?"] |
| 翻译后的路径 | /about、/ueber-uns | ["en", "/about"]、["de", "/ueber-uns"] |
| 子域名 | example.com、de.example.com | ["en", "https://example.com/:path(.*)?"]、["de", "https://de.example.com/:path(.*)?"] |
| 无前缀(cookie/请求头) | /dashboard | ["en", "/dashboard/:path(.*)?"]、["de", "/dashboard/:path(.*)?"] |
“无前缀”适用于仪表盘等需要登录的区域:URL 保持不变,内容则根据 cookie 或请求头中存储的用户偏好进行本地化。
语言区域前缀
https://example.com/about
https://example.com/de/about
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "cookie"],
urlPatterns: [
{
pattern: "/",
localized: [
["de", "/de"],
["en", "/"],
],
},
{
pattern: "/:path(.*)?",
localized: [
["de", "/de/:path(.*)?"],
// 务必将最不具体的路径放在最后匹配
["en", "/:path(.*)?"],
],
},
],
});
精确根路径规则会生成 /de 和 /de#section,而不是 /de/ 和
/de/#section。它必须放在通配符规则之前,因为最先匹配的
模式优先生效。
为什么通配符模式总能解析:模式 /:path(.*)? 会匹配所有未被精确根路径规则处理的路径。用户访问 /about (不带语言区域前缀) 时,该路径会匹配英语模式并解析为 en。如果你未指定 urlPatterns,Paraglide 内置的默认路由同样使用通配符。
[!NOTE]
extractLocaleFromUrl()仅在 Paraglide 内置的默认路由模式下不区分大小写。该模式从第一个路径段读取语言区域并进行规范化 (因此/DE/about会解析为de) 。一旦提供了自定义的urlPatterns,匹配就会改为遵循标准的URLPattern语义,此时路径大小写必须与你配置的模式完全一致。
为所有语言区域添加前缀 (SvelteKit、Next.js)
SvelteKit 等框架使用必需的 [locale] 路径段来实现按语言区域划分的路由,因此所有语言区域都需要前缀 (/en/about、/de/about) 。如果基础语言区域也要加前缀,请在通配符之前为根路径添加一个显式模式:
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "cookie"],
urlPatterns: [
{
pattern: "/",
localized: [
["en", "/en"],
["fr", "/fr"],
],
},
{
pattern: "/:path(.*)?",
localized: [
["en", "/en/:path(.*)?"],
["fr", "/fr/:path(.*)?"],
],
},
],
});
专用的根路径模式会生成 /en 和 /fr,而不是 /en/ 和
/fr/。它还能避免重定向循环,并防止无谓地跳转到
非规范的首页 URL。
不带语言区域前缀的路由
某些路由 (如 /dashboard 或 /app) 可能需要 i18n,但 URL 中不应包含语言区域前缀。只需为所有语言区域配置相同的路径即可:
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "cookie", "baseLocale"],
urlPatterns: [
// 仪表盘路由:不加语言区域前缀
{
pattern: "/dashboard/:path(.*)?",
localized: [
["en", "/dashboard/:path(.*)?"],
["de", "/dashboard/:path(.*)?"], // 所有语言区域使用相同路径
],
},
// 其他路由:使用语言区域前缀
{
pattern: "/:path(.*)?",
localized: [
["de", "/de/:path(.*)?"],
["en", "/:path(.*)?"],
],
},
],
});
使用此配置后:
- 无论语言区域如何,
/dashboard/*URL 都保持不变 - 语言区域由 cookie 或其他回退策略确定
- 其他路由 (如
/about) 使用基于 URL 的语言区域 (/de/about)
[!TIP]对于完全不需要 i18n 的路由 (如
/api) ,应直接绕过中间件。参见从中间件中排除路由。
翻译后的路径名
如果你希望对 URL 的结构和路径段进行本地化,可以为每个语言区域配置不同的模式。这样就能实现按语言区分的路由,例如英语使用 /about,德语使用 /ueber-uns。
https://example.com/about
https://example.com/ueber-uns
下面是一个翻译路径段的简单示例:
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "cookie"],
urlPatterns: [
// 指定需要翻译的路由
{
pattern: "/about",
localized: [
["en", "/about"],
["de", "/ueber-uns"],
],
},
{
pattern: "/products/:id",
localized: [
["en", "/products/:id"],
["de", "/produkte/:id"],
],
},
// 未翻译路由的通配符:所有语言区域使用相同路径
{
pattern: "/:path(.*)?",
localized: [
["en", "/:path(.*)?"],
["de", "/:path(.*)?"],
],
},
],
});
[!NOTE]当所有语言区域都使用相同路径时 (如上文的通配符回退) ,仅凭 URL 无法确定语言区域。对于这些路由,Paraglide 会使用你配置的回退策略 (cookie、请求头 等) 。如果希望所有路由都通过 URL 检测语言区域,请改用带前缀的回退模式,例如
/de/:path(.*)?。
基于域名的本地化
https://example.com/about
https://de.example.com/about
使用基于域名的路由时,需要为 localhost 和生产环境分别配置模式。如果没有 localhost 模式,生产域名的模式在本地开发时将无法匹配,URL 本地化也就不会生效。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "cookie"],
urlPatterns: [
// 本地环境(localhost):本地无法使用子域名,因此改用路径前缀
{
pattern: "http://localhost::port?/:path(.*)?",
localized: [
["en", "http://localhost::port?/en/:path(.*)?"],
["de", "http://localhost::port?/de/:path(.*)?"],
],
},
// 生产环境:使用子域名
{
pattern: "https://example.com/:path(.*)?",
localized: [
["en", "https://example.com/:path(.*)?"],
["de", "https://de.example.com/:path(.*)?"],
],
},
],
});
添加基础路径
你可以在 URL 模式中添加基础路径,让本地化 URL 共用同一个基础路径。
例如,将基础路径设为 "shop" 时:
localizeHref("/about")→/shop/en/aboutdeLocalizeHref("/shop/en/about")→/about
{shop/}? 使用的是 URLPattern 的可选组语法:
{...}创建一个组?使该组变为可选 (匹配零次或一次)- 末尾的
/放在组内,这样只有基础路径存在时才会出现
这样,该模式就能同时匹配 /about 和 /shop/about。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "cookie"],
urlPatterns: [
{
pattern: "/{shop/}?:path(.*)?",
localized: [
["en", "/{shop/}?en/:path(.*)?"],
["de", "/{shop/}?de/:path(.*)?"],
],
},
],
});
| 原始 URL | 本地化 URL (EN) | 本地化 URL (DE) |
|---|---|---|
/about | /shop/en/about | /shop/de/about |
/shop/about | /shop/en/about | /shop/de/about |
在特定语言区域中禁用 URL 模式
将某些路由映射到你的 404 页面,即可让它们在特定语言区域中无法访问。
https://example.com/specific-path // 英语版可访问
https://example.com/de/specific-path // 德语版重定向到 404
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "cookie"],
urlPatterns: [
// 仅英语可用的路由
{
pattern: "/specific-path",
localized: [
["en", "/specific-path"],
["de", "/de/404"], // 德语用户会被重定向到 404
],
},
// 兜底匹配其他所有路由
{
pattern: "/:path(.*)?",
localized: [
["de", "/de/:path(.*)?"],
["en", "/:path(.*)?"],
],
},
],
});
当德语用户访问 /specific-path 时,会被重定向到 /de/404。这适用于以下场景:
- 仅以特定语言提供的内容
- 按语言区域逐步上线的功能
- 来自特定地区的旧版 URL
实际案例
多租户应用
如果你的 SaaS 平台为每个客户分配了不同的域名或子域名,且各客户需要不同的默认语言区域或支持语言,请参阅多租户指南。
重定向
服务端的 paraglideMiddleware() 已经通过 shouldRedirect() 辅助函数让文档请求保持规范 URL。如果需要在单页应用中实现相同的行为,或在 SSR 应用中进行客户端导航之后做同样的处理,可以在客户端调用同一个辅助函数。
在浏览器中传入 { url },在服务端传入 { request }。如果代理或负载均衡器在请求到达应用之前修改了浏览器看到的 URL,还需要传入 effectiveRequestUrl。
[!NOTE]客户端的
shouldRedirect()不能替代首次文档请求时的服务端语言区域检测。如果你的 SSR 应用只把语言区域存储在localStorage中,服务端在 hydration 之前无法读取该值。这种情况下,初始 URL 仍可能根据preferredLanguage、cookie或url进行规范化。如果首次请求必须遵循已存储的覆盖设置,请改用服务端可读取的策略,例如cookie。
通用 SPA
import { shouldRedirect } from "./paraglide/runtime.js";
async function checkRedirect() {
const decision = await shouldRedirect({ url: window.location.href });
if (decision.shouldRedirect) {
window.location.href = decision.redirectUrl.href;
}
}
// 在路由变化或应用初始化时调用
checkRedirect();
TanStack Router
import { redirect } from "@tanstack/router";
import { shouldRedirect } from "./paraglide/runtime.js";
export const beforeLoad = async ({ location }) => {
const decision = await shouldRedirect({ url: location.href });
if (decision.shouldRedirect) {
throw redirect({ to: decision.redirectUrl.href });
}
};
SvelteKit
如果需要在 SvelteKit 中于客户端导航后重新同步 URL,请将 shouldRedirect() 放在根 +layout.svelte 中。这只影响 hydration 之后的客户端,初始的 SSR 文档请求仍由 paraglideMiddleware() 处理。
由此产生的每次重定向都应视为文档导航,同源 URL 也不例外。切换语言区域的重定向不要使用 SvelteKit 的 goto():完整导航才能确保文档级状态 (如 <html lang> 和 dir) 、服务端渲染的数据以及客户端状态都与新的语言区域一致。
[!WARNING]
setLocale(..., { reload: false })有意不支持这种场景。切换语言区域的 URL 必须加载新文档;使用这一应急手段或 SvelteKit 的goto()可能会残留过时的文档外壳。
<script lang="ts">
import { afterNavigate } from "$app/navigation";
import { onMount } from "svelte";
import { shouldRedirect } from "$lib/paraglide/runtime";
async function syncLocaleUrl(url: string) {
const decision = await shouldRedirect({ url });
if (decision.shouldRedirect && decision.redirectUrl) {
window.location.href = decision.redirectUrl.href;
}
}
onMount(() => {
void syncLocaleUrl(window.location.href);
});
afterNavigate((navigation) => {
if (navigation.to) {
void syncLocaleUrl(navigation.to.url.href);
}
});
</script>
部署在代理后面的服务器
将浏览器实际访问的 URL 作为 effectiveRequestUrl 传入。该值应根据可信的代理或框架元数据推导得出。
import { shouldRedirect } from "./paraglide/runtime.js";
export async function handle(request: Request) {
const effectiveRequestUrl = new URL(request.url);
effectiveRequestUrl.protocol = "https:";
effectiveRequestUrl.host = "app.example.com";
const decision = await shouldRedirect({ request, effectiveRequestUrl });
if (decision.shouldRedirect) {
return Response.redirect(decision.redirectUrl, 307);
}
return render(request, decision.locale);
}
故障排查
调试 URL 模式
要验证模式是否按预期工作:
-
可视化测试模式:访问 urlpattern.com,粘贴你的模式和测试 URL,查看哪些能匹配
-
在中间件中记录语言区域解析过程:
// 在现有的中间件处理函数中添加日志输出
paraglideMiddleware(request, ({ request, locale }) => {
console.log(`URL: ${request.url} → Locale: ${locale}`);
return yourAppHandler(request); // 现有的处理函数
});
- 测试 URL 辅助函数 - 在应用代码中打印
localizeHref()的输出:
import { localizeHref } from "./paraglide/runtime.js";
console.log(localizeHref("/about", { locale: "de" }));
// 应输出 "/de/about" 或 "/ueber-uns",取决于你的模式配置
使用 URL 通配符时的策略顺序
使用 /:path(.*)? 这类通配符模式 (默认即是如此) 时,URL 策略总会解析出一个语言区域。因此它在策略数组中相当于一个"终止条件":排在它之后的策略永远不会被执行。
如果你希望用户偏好 (来自 localStorage、cookie 等) 优先于 URL,请把这些策略放在 URL 策略之前:
// 优先检查用户偏好
strategy: ["localStorage", "preferredLanguage", "url"];
// localStorage 永远不会被检查,因为 URL 总能解析出 locale
strategy: ["url", "localStorage", "preferredLanguage"];
在 SSR 应用中,这只适用于服务器在首次文档请求时就能读取到的策略。localStorage 要到 hydration 之后才会参与,而服务器可以直接读取 cookie 和 preferredLanguage。
在 URL 模式中排除路径
URLPattern 不支持负向先行断言 (negative lookahead) 正则表达式,因此无法直接在 urlPatterns 中排除 /api/* 这类路径。
请改用 routeStrategies。这种做法很常见:公开页面通过 URL 进行本地化,而不带前缀的私有页面 (如 /dashboard) 则从 cookie 中解析语言区域。
compile({
project: "./project.inlang",
outdir: "./src/paraglide",
strategy: ["url", "cookie", "baseLocale"],
routeStrategies: [
{ match: "/dashboard/:path(.*)?", strategy: ["cookie", "baseLocale"] },
{ match: "/api/:path(.*)?", exclude: true },
],
});
详情请参阅从中间件中排除路由。
模式的顺序很重要
URL 模式按照其在 urlPatterns 数组中的出现顺序依次求值,系统会使用第一个匹配该 URL 的模式。因此,更具体的模式应放在更通用的模式之前。
为简洁起见,以下示例只展示 urlPatterns 数组,省略了外层的 compile() 调用。
urlPatterns: [
// 错误顺序:通配符模式会匹配所有内容,
// 导致具体模式永远不会被执行到
{
pattern: "https://example.com/:path(.*)?", // 这会匹配任意路径
localized: [
["en", "https://example.com/:path(.*)?"],
["de", "https://example.com/de/:path(.*)?"],
],
},
{
pattern: "https://example.com/blog/:id", // 永远不会执行到这里
localized: [
["en", "https://example.com/blog/:id"],
["de", "https://example.com/de/blog/:id"],
],
},
];
// 正确顺序:先写具体模式,再写更通用的模式
urlPatterns: [
{
pattern: "https://example.com/blog/:id", // 具体模式在前
localized: [
["en", "https://example.com/blog/:id"],
["de", "https://example.com/de/blog/:id"],
],
},
{
pattern: "https://example.com/:path(.*)?", // 通用模式在后
localized: [
["en", "https://example.com/:path(.*)?"],
["de", "https://example.com/de/:path(.*)?"],
],
},
];
本地化模式的顺序同样重要
在每个模式的 localized 数组中,各语言区域模式的顺序同样重要。本地化 URL 时,会使用目标语言区域中第一个匹配的模式。同理,去本地化 URL 时,也会按顺序依次检查模式。
在基于路径的本地化中,如果某个语言区域带前缀 (如 /de/) 而另一个不带,这一点尤为重要。此时应将更具体的模式 (带前缀的) 放在前面。
// 错误顺序:第一个模式过于宽泛
{
pattern: "https://example.com/:path(.*)?",
localized: [
["en", "https://example.com/:path(.*)?"], // 这会匹配任意路径
["en", "https://example.com/en/blog/:id"], // 这个具体模式永远不会被匹配到
],
}
// 正确顺序:先放具体模式,再放更宽泛的模式
{
pattern: "https://example.com/:path(.*)?",
localized: [
["en", "https://example.com/en/blog/:id"], // 具体模式在前
["en", "https://example.com/:path(.*)?"], // 宽泛模式在后
],
}
// 去本地化的错误顺序:通用模式在前会导致问题
{
pattern: "/:path(.*)?",
localized: [
["en", "/:path(.*)?"], // 通用模式会匹配所有路径,包括 "/de/about"
["de", "/de/:path(.*)?"], // 去本地化时,带前缀的模式永远不会被匹配到
],
}
// 正确顺序:带前缀的更具体模式应放在前面
{
pattern: "/:path(.*)?",
localized: [
["de", "/de/:path(.*)?"], // 带前缀的具体模式在前
["en", "/:path(.*)?"], // 通用模式在后
],
}
末尾斜杠
URLPattern 会将 /about 和 /about/ 视为不同的路径。你可以通过 trailingSlash 编译器选项,让 Paraglide 在匹配前和生成后对本地化 URL 做规范化处理:
paraglideVitePlugin({
project: "./project.inlang",
outdir: "./src/paraglide",
trailingSlash: "never", // 或 "always"
});
"never" 会移除末尾斜杠,"always" 会添加末尾斜杠。根路径 / 始终保持为 /,查询参数和哈希也会保留。已有的自定义 urlPatterns 可以沿用各自的末尾斜杠风格;设置此选项后,Paraglide 会把另一种末尾斜杠形式视为别名。未匹配的自定义模式保持不变。
省略 trailingSlash 时,默认路由会保留末尾斜杠 (/about/ 变为 /de/about/,/about 则变为 /de/about) 。使用自定义 urlPatterns 时,匹配仍是精确匹配,生成的路径由配置的模式决定。如果你的框架已经负责末尾斜杠的规范化,这种做法会很有用。
框架的规范化不会改变 localizeHref() 或
localizeUrl() 生成的 URL。如果你省略了 trailingSlash,而 Paraglide 生成的是 /de/,
你的框架却把 /de 视为规范 URL,那么访问 /de/#section 时
可能会触发不必要的导航或重定向,而不是只更新片段。
可以参照
语言区域前缀 中的做法,在通配符之前添加精确的根路径模式,或者将 trailingSlash 配置为与
框架的规范 URL 策略一致。
如果 Paraglide 和你的框架都会规范化末尾斜杠,请为两者配置相同的策略,以免出现重定向循环。
