Nginx use different path based on language code

Viewed 17

I have a website in two languages English and Spanish.

Each language website is hosted in a different directive

/var/www/html/en-US/      -> English version
/var/www/html/es/         -> Spanish version

Using the following nginx configuration to redirect user to language specific directory

https://example.com/en/     -> Serve English version
https://example.com/es/     -> Serve Spanish version

and the configuration is

map $http_accept_language $accept_language {
    ~*^es es;
    ~*^en en;
}


server {
    server_name                  example.com;

    root /var/www/html/en-US;

    # 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;

    location ~ ^/en {
        root             /var/www/html/en-US;
        index            index.html;
        try_files        $uri $uri/ =404;
    }

    location ~ ^/es {
        root             /var/www/html/es;
        index            index.html;
        try_files        $uri $uri/ =404;
    }
}

Now, accessing https://example.com redirects to https://example.com/en but gives 404.

1 Answers

Solved the issue by making the following changes

server {
    server_name                  example.com;

    root /var/www/html/en-US/;

    # 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;

    location /en/ {
        alias            /var/www/html/en-US/;
        try_files        $uri $uri/ =404;
    }

    location /es/ {
        alias            /var/www/html/es/;
        try_files        $uri $uri/ =404;
    }
}
Related