I have a multi-lingual website and want the URL schema to work like
https://example.com/ -> Load english version
https://example.com/path -> Load english version
https://example.com/es/ -> Load spanish version
https://example.com/es/path -> Load spanish version
and using the nginx configuration
map $http_accept_language $accept_language {
~*^es es;
~*^en en;
}
server {
server_name example.com;
location /docs {
alias /var/www/html/app-frontend/documentation/;
try_files $uri$args $uri$args/ /docs/index.html;
}
# Fallback to default language if no preference defined by browser
if ($accept_language ~ "^$") {
set $accept_language "en";
}
# 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 / {
alias /var/www/html/app-frontend/en-US/;
index index.html;
try_files $uri $uri/ /index.html = 404;
}
location /es/ {
alias /var/www/html/app-frontend/es/;
index index.html;
try_files $uri $uri/ /index.html = 404;
}
}
I want the nginx to redirect to language code if the detected language is not english. But the above configuration, redirects to /en/
when the language detected is english.
How can I point the root path (without language code) to the english version?
Tried moving rewrite
statement inside if
check as follows
if ($accept_language !~ "en") {
rewrite ^/$ /$accept_language/ permanent;
}
# rewrite ^/$ /$accept_language/ permanent;
It works fine. But it looks like the configuration can be more optimized.