如何在Nginx中进行多语言配置?

时间:2017-09-19 18:36:07

标签: redirect nginx multilingual proxypass

我有以下Nginx配置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;
    }
}

我该怎么做?

1)根据语言,将所有/*个请求传递给/en/*/ru/*

2)将所有/en/*传递给/usr/share/nginx/html/<request>?lang=en/ru/*传递给/usr/share/nginx/html/<request>?lang=ru

3)如果语言不是enru /*/en/*的所有function exportToExcel(tableID){ var tab_text="<table border='2px'><tr bgcolor='#87AFC6' style='height: 75px; text-align: center; width: 250px'>"; var textRange; var j=0; tab = document.getElementById(tableID); // id of table for(j = 0 ; j < tab.rows.length ; j++) { tab_text=tab_text; tab_text=tab_text+tab.rows[j].innerHTML.toUpperCase()+"</tr>"; //tab_text=tab_text+"</tr>"; } tab_text= tab_text+"</table>"; tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table tab_text= tab_text.replace(/<img[^>]*>/gi,""); //remove if u want images in your table tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); //remove input params var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer { txtArea1.document.open("txt/html","replace"); txtArea1.document.write( 'sep=,\r\n' + tab_text); txtArea1.document.close(); txtArea1.focus(); sa=txtArea1.document.execCommand("SaveAs",true,"asd.xls"); } else { sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); } return (sa); } 次请求的路径?

1 个答案:

答案 0 :(得分:0)

您需要为根网址和您的语言部分应用两个单独的location块,如下所示:

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;
    ...
}

首先location阻止回答问题1)和3)其中根网址将被$lang部分中的map变量重写,最后一个定义您将使用en语言作为默认语言。

第二个location阻止是您的问题2)您接受语言参数作为双字符路径,然后重写您的网址以满足您的需求。

此代码可能不是100%有效,但它应该给你一个想法。

<强>更新

嗯,实际上你可以一次性完成这件事:

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