nginx:使用 @angular/localize 提供多语言 I18N Angular UI
这是我的 nginx 配置,通过 Docker 自动提供 de 和 en 多语言国际化的 Angular UI。
如果用户未直接访问特定语言版本的站点,将被重定向到与浏览器语言设置匹配的版本(默认为 de)。
添加额外语言时,需要更新 nginx.conf 文件:复制一个新的 location 块用于附加语言,并在 $accept_language 映射中添加一行以自动接受新语言。
Nginx 配置文件
nginx_i18n_conf.conf
map $http_accept_language $accept_language {
~*^de de;
~*^en en;
default de;
}
server {
listen 80 default_server;
root /app/browser;
index index.html;
# 禁用访问日志和错误日志
access_log off;
error_log /var/log/nginx/error.log;
# 将 "/" 重定向到浏览器首选语言的 Angular 应用
add_header Cache-Control "public, max-age=180";
# 提供各语言版本
location /en/ {
try_files $uri$args /en/index.html?$args;
}
location /de/ {
try_files $uri$args /de/index.html?$args;
}
# 重定向到默认语言
location = / {
return 302 /$accept_language/;
}
# 将其他 URL 重定向到默认语言
location / {
return 302 /$accept_language/$uri$args;
}
}Angular 构建脚本
在构建 Docker 镜像之前调用此 shell 脚本:
build_angular_i18n.sh
ng build --aot --named-chunks=true --optimization --output-hashing=all --stats-json $@Dockerfile
Dockerfile
FROM nginx:1.27.5-alpine-slim
WORKDIR /app
# 复制配置
COPY nginx.conf /etc/nginx/conf.d/default.conf
# 复制 dist 文件到 /app
COPY dist/mytheme/. ./If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow