Angular 部署多个语言环境

2022-07-08 11:13 更新

部署多个语言环境

如果 ​myapp ​是包含项目可分发文件的目录,你通常会在语言环境目录中为不同的语言环境提供不同的版本,比如法语版的 ​myapp/fr​ 和西班牙语版的 ​myapp/es​。

带有 ​href​ 属性的 HTML ​base ​标签指定了相对链接的基本 URI 或 URL。如果你将工作空间构建配置文件 ​angular.json​ 中的 ​"localize"​ 选项设置为 ​true ​或语言环境 ID 数组,CLI 会为应用程序的每个版本调整 base ​href​。要为应用程序的每个版本调整 base ​href​,CLI 会将语言环境添加到配置的 ​"baseHref"​ 中。在工作区配置文件 ​angular.json​ 中为每个语言环境指定 ​"baseHref"​。以下示例展示了设置为空字符串的 ​"baseHref"​。

"projects": {
    "angular.io-example": {
      // ...
      "i18n": {
        "sourceLocale": "en-US",
        "locales": {
          "fr": {
            "translation": "src/locale/messages.fr.xlf",
            "baseHref": ""
          }
        }
      },
      "architect": {
        // ...
      }
    }
  }
  // ...
}

此外,要在编译时声明 base ​href​,请将在 CLI 中使用带有 ​--baseHref​ 选项的 ​ng build​ 。

配置服务器

多语言的典型部署方式是为来自不同子目录的每种语言提供服务。使用 ​Accept-Language​ HTTP 标头将用户重定向到浏览器中定义的首选语言。如果用户未定义首选语言,或者首选语言不可用,则服务器将回退到默认语言。要更改语言,就转到另一个子目录。 子目录的更改通常使用应用程序中实现的菜单进行。

Nginx 范例

以下示例展示了 Nginx 配置。

http {
    # Browser preferred language detection (does NOT require
    # AcceptLanguageModule)
    map $http_accept_language $accept_language {
        ~*^de de;
        ~*^fr fr;
        ~*^en en;
    }
    # ...
}

server {
    listen 80;
    server_name localhost;
    root /www/data;

    # Fallback to default language if no preference defined by browser
    if ($accept_language ~ "^$") {
        set $accept_language "fr";
    }

    # Redirect "/" to Angular application in the preferred language of the browser
    rewrite ^/$ /$accept_language permanent;

    # Everything under the Angular application is always redirected to Angular in the
    # correct language
    location ~ ^/(fr|de|en) {
        try_files $uri /$1/index.html?$args;
    }
    # ...
}

Apache 范例

以下示例展示了 Apache 配置。

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot /www/data
    <Directory "/www/data">
        RewriteEngine on
        RewriteBase /
        RewriteRule ^../index\.html$ - [L]

        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule (..) $1/index.html [L]

        RewriteCond %{HTTP:Accept-Language} ^de [NC]
        RewriteRule ^$ /de/ [R]

        RewriteCond %{HTTP:Accept-Language} ^en [NC]
        RewriteRule ^$ /en/ [R]

        RewriteCond %{HTTP:Accept-Language} !^en [NC]
        RewriteCond %{HTTP:Accept-Language} !^de [NC]
        RewriteRule ^$ /fr/ [R]
    </Directory>
</VirtualHost>


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号