How can I make multi language config in Nginx?

4.5k Views Asked by At

I have following Nginx config default.conf:

map $http_accept_language $browser_lang {
        default en;
        ~ru ru;
}
map $cookie_lang $lang {
    default $browser_lang;
    ~en en;
    ~ru ru;
}

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;

        try_files $uri $uri/ /index.html;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

How can I do following:

1) Pass all /* requests to /en/* or /ru/* depending of language?

2) Pass all /en/* to /usr/share/nginx/html/<request>?lang=en and /ru/* to /usr/share/nginx/html/<request>?lang=ru?

3) If language is not en and ru path to all /* requests to /en/*?

1

There are 1 best solutions below

0
On

You need to apply two separate location blocks for root url and for your language sections like so:

location = / {
    rewrite ^ $scheme://$host/$lang$uri$is_args$args break;
}

location ~ '^/(?<lang_code>[\w-]{2})' {
    rewrite ^/(?<lang_code>[\w-]{2})/(.*)$ /$1?lang=$lang_code last;

    ...
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
    ...
}

First location block answers to you questions 1) and 3) where the root url will be rewritten with your $lang variable in it that comes from map section and the last one defines that you will be using en language as default.

Second location block is for your questions 2) where you accept your language param as two-char path and then rewrite your url to suit your needs.

This code may not be 100% working, but it should give you an idea.

UPDATE

Well, actually you can do this in one single pass:

location / {
    if ($uri !~ '^/([a-z]{2})(/.*)?$') {
        rewrite ^ $scheme://$host/$lang$uri permanent;
        rewrite ^/([a-z]{2})(/.*)?$ /$2?lang=$1;
    }
    ...
}