How to use nginx to deliver Multi-Language I18N Angular UIs using @angular/localize

This is my nginx config which automatically serves a de and en multilingually internationalized Angular UI via Docker.

If the user didn’t already access a specific-language version of the site, they will be redirected to the version that matches their browser’s language settings (or a default of de).

When adding extra languages, you need to update the nginx.conf file by copying a new location block for the additional language, plus the $accept_language line to accept a new language automatically.

Nginx config file

map $http_accept_language $accept_language {
    ~*^de de;
    ~*^en en;
    default de;
}
server {
    listen 80 default_server;
    root /app/browser;
    index index.html;
    # Disable access & error logs
    access_log off;
    error_log /var/log/nginx/error.log;
    # Redirect "/" to Angular application in the preferred language of the browser
    add_header Cache-Control "public, max-age=180";
    # Serve individual languages
    location /en/ {
        try_files $uri$args /en/index.html?$args;
    }
    location /de/ {
        try_files $uri$args /de/index.html?$args;
    }
    # Redirect to default language
    location = / {
      return 302 /$accept_language/;
    }

    # Redirect other URLs to default language
    location / {
      return 302 /$accept_language/$uri$args;
    }
}

Angular buildscript

Call this shell script just before building the Docker image

ng build --aot --named-chunks=true --optimization --output-hashing=all --stats-json $@

Dockerfile

FROM nginx:1.27.5-alpine-slim

WORKDIR /app
# Copy config
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Copy dist files to /app
COPY dist/mytheme/. ./