You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Firebase Hosting与Angular中实现基于语言头的自动baseHref跳转

正确实现Angular i18n自动语言跳转(Firebase环境)

问题核心

之前的Firebase Functions代码未判断请求路径是否已包含语言前缀,导致重复添加/sv或/en。解决关键是:只对根路径(/)做自动跳转,已带语言前缀的请求直接放行。

修正后的Firebase Functions代码

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

exports.i18nRedirect = functions.https.onRequest((req, res) => {
  const path = req.path;
  
  // 跳过已带语言前缀的请求,避免重复跳转
  const hasValidLangPrefix = /^\/(sv|en)(\/.*)?$/.test(path);
  if (hasValidLangPrefix) {
    const targetPath = path.endsWith('/') ? `${path}index.html` : `${path}/index.html`;
    return res.sendFile(targetPath, { root: './public' });
  }

  // 仅处理根路径的自动语言跳转
  if (path === '/') {
    const acceptLanguage = req.headers['accept-language'];
    let targetLang = 'en'; // 默认英语

    if (acceptLanguage) {
      // 解析请求头,优先匹配瑞典语(含sv-SE等变体)
      const langList = acceptLanguage.split(',').map(item => item.split(';')[0].trim());
      if (langList.some(lang => lang.startsWith('sv'))) {
        targetLang = 'sv';
      }
    }

    // 302临时跳转(如需永久跳转可改用301)
    return res.redirect(302, `/${targetLang}`);
  }

  // 处理其他静态资源请求(如/favicon.ico、css/js文件等)
  return res.sendFile(path, { root: './public' });
});

配套的firebase.json配置

仅将根路径请求转发到Functions,带语言前缀的请求直接由Firebase Hosting处理静态资源:

{
  "hosting": {
    "public": "dist/your-project-name",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      // 根路径请求交给Functions处理跳转
      {
        "source": "/",
        "function": "i18nRedirect"
      },
      // 瑞典语路径直接返回对应index.html
      {
        "source": "/sv/**",
        "destination": "/sv/index.html"
      },
      // 英语路径直接返回对应index.html
      {
        "source": "/en/**",
        "destination": "/en/index.html"
      },
      // 其他静态资源直接返回
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  },
  "functions": {
    "source": "functions"
  }
}

Angular编译配置确认

确保编译时生成独立的语言目录,angular.json关键配置:

"i18n": {
  "sourceLocale": "en",
  "locales": {
    "sv": "src/locale/messages.sv.xlf"
  }
},
"architect": {
  "build": {
    "configurations": {
      "production": {
        // ...生产环境基础配置
      },
      "sv": {
        "localize": ["sv"],
        "outputPath": "dist/your-project-name/sv"
      },
      "en": {
        "localize": ["en"],
        "outputPath": "dist/your-project-name/en"
      }
    }
  }
}

编译命令:

ng build --configuration=production,sv
ng build --configuration=production,en

验证要点

  • 访问根域名mypage.com,自动跳转到/sv或/en(取决于浏览器Accept-Language设置)
  • 直接访问mypage.com/sv或mypage.com/en,无重复跳转,正常加载对应语言页面
  • 访问带路由的路径(如mypage.com/sv/about),正常加载Angular路由页面

内容的提问来源于stack exchange,提问作者pb4now

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 18:12:25