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

Angular SSR多语言站点:默认语言根路由及站点文件路径调整

解决Angular SSR多语言网站默认路由与静态文件位置问题

一、将默认语言(EN)路由设为根目录

1. 配置路由模块

在app-routing.module.ts中,给非默认语言路由添加前缀,默认语言直接使用根路径:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path: '', component: HomeComponent }, // EN语言的根路由
  { path: 'fr', loadChildren: () => import('./fr/fr.module').then(m => m.FrModule) },
  { path: 'de', loadChildren: () => import('./de/de.module').then(m => m.DeModule) },
  { path: '**', redirectTo: '' } // 兜底重定向到默认语言根路径
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    initialNavigation: 'enabledBlocking', // SSR必需配置
    useHash: false
  })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2. 调整语言切换逻辑

在语言切换组件/服务中,处理默认语言的跳转逻辑:

switchLanguage(lang: string) {
  const targetPath = lang === 'en' ? '/' : `/${lang}`;
  this.router.navigate([targetPath]);
  localStorage.setItem('activeLang', lang);
}

3. SSR服务器端适配(以Express为例)

修改server.ts,确保服务器能正确匹配默认语言的请求:

server.get('*', (req, res) => {
  const pathSegments = req.path.split('/').filter(seg => seg);
  const targetLang = ['fr', 'de'].includes(pathSegments[0]) ? pathSegments[0] : 'en';
  const renderPath = targetLang === 'en' ? 'index' : `${targetLang}/index`;
  
  res.render(renderPath, { req, res });
});

二、将sitemap、robot.txt移至根目录

1. 调整文件生成路径

如果使用第三方工具或自定义脚本生成静态文件,直接将输出路径指定为项目dist根目录:

// 示例自定义sitemap生成脚本
const fs = require('fs');
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url><loc>https://mywebsite.com/</loc></url>
  <url><loc>https://mywebsite.com/fr/</loc></url>
  <url><loc>https://mywebsite.com/de/</loc></url>
</urlset>`;

fs.writeFileSync('./dist/sitemap.xml', sitemap);

2. 构建后移动文件(备选方案)

如果无法直接修改生成路径,在package.json的构建命令后追加移动指令:

{
  "scripts": {
    "build:ssr": "ng build --prod && ng run my-app:server:prod && npm run move-static",
    "move-static": "cp ./dist/en/sitemap.xml ./dist/ && cp ./dist/en/robot.txt ./dist/"
  }
}

3. 服务器端静态文件托管配置

在server.ts中确保根目录静态文件可被访问:

server.use(express.static('dist', { index: false }));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 15:27:06