在我的 Angular 项目中,我为“sv”(瑞典语)和“en”设置了 i18n。
我想要的是在访问 mypage.com 时,将“/sv”或“/en”添加到 baseHref 这样正确的index.html就会从基于“接受语言”的Firebase托管加载,换句话说,瑞典用户将获得“mypage.com/sv”,而其他所有人将加载mypage.com/en。
我做了一些挖掘,似乎这并不是 Firebase 托管自动带来的,必须在 Angular 或 Firebase 函数中添加一些逻辑。
在角度中添加逻辑完全失败(请记住,我希望它自动发生,而不是用户在下拉列表中选择的东西)
...以及 firebase 函数的逻辑,尽管它在最简单的级别上工作,但它扰乱了我的路由(在不应该添加大量“/sv”到路径时+感觉像是一个修复)。此修复的以下代码:
exports.redirectBasedOnLanguage = functions.https.onRequest((req:any, res:any) => {
// Default to English
let language = 'en';
// Check for the Accept-Language header and prefer Swedish if present
const acceptLanguage = req.headers['accept-language'];
if (acceptLanguage && acceptLanguage.startsWith('sv')) {
language = 'sv';
}
// Construct the redirect URL based on the detected language
// Note: You might want to adjust the path construction based on your URL structure
const targetUrl = `/${language}${req.path}`;
// Perform the redirection
res.redirect(302, targetUrl);
});
我的 firebase.json: 对于上述解决方案:
"rewrites": [
{
"source": "**",
"function": "redirectBasedOnLanguage"
}
];
并且在没有任何 firebaseFunctions 修复的情况下进行设置(当遵循文档时):
"rewrites": [
{
"source": "/sv{,/**}",
"destination": "/sv/index.html"
},
{
"source": "/sv-SE{,/**}",
"destination": "/sv/index.html"
},
{
"source": "**",
"destination": "/en/index.html"
}
]
正确的处理方法是什么?
您可能想看看这个 Firebase 托管 i18n 配置。