How to rewrite location in nginx depending on the client-browser's language?

前端 未结 10 1949
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 17:25

How to rewrite location in nginx depending on the client-browser\'s language?

For example: My browser accept-language is \'uk,ru,en\'. When I request locati

10条回答
  •  温柔的废话
    2020-12-02 17:55

    I know this is a very old thread, but I found it when trying to solve the same problem. Just wanted to share the solution I finally came with. It is different to the ones published above as if there are several languages mentioned in the Accept-Language, it will pick the first mentioned among the ones we can serve.

        #
        # Determine what language to redirect to
        # this sets the value of $lang variable to the language depending on the contents of Accept-Language request header
        # the regexp pattern automatically matches a known language that is not preceded by another known language
        # If no known language is found, it uses some heuristics (like RU for (uk|be|ky|kk|ba|tt|uz|sr|mk|bg) languages)
        #
        map $http_accept_language $lang {
            default en;
            "~*^((|,)\s*(?!(ru|es|fr|pt|en))\w+(-\w+)?(;q=[\d\.]+)?)*(|,)\s*en\b" en;
            "~*^((|,)\s*(?!(ru|es|fr|pt|en))\w+(-\w+)?(;q=[\d\.]+)?)*(|,)\s*es\b" es;
            "~*^((|,)\s*(?!(ru|es|fr|pt|en))\w+(-\w+)?(;q=[\d\.]+)?)*(|,)\s*ru\b" ru;
            "~*^((|,)\s*(?!(ru|es|fr|pt|en))\w+(-\w+)?(;q=[\d\.]+)?)*(|,)\s*fr\b" fr;
            "~*^((|,)\s*(?!(ru|es|fr|pt|en))\w+(-\w+)?(;q=[\d\.]+)?)*(|,)\s*pt\b" pt;
            "~*(^|,)\s*(uk|be|ky|kk|ba|tt|uz|sr|mk|bg)\b" ru;
            "~*(^|,)\s*(ca|gl)\b" es;
        }
    
        ...
    
        rewrite (.*) $1/$lang;
    

    The limitation of this solution is that it assumes the languages in the Accept-Language header are listed in the order of their preference. Usually this is true, but it is not officially required. For example, if the header is "Accept-Language: da, en-US;q=0.1, pt-BR;q=1", the variable $lang will be set to "en" because it comes before "pt" even though pt has larger weight.

    Choosing the right language taking into account all the weights does not seem to be possible in nginx without external scripts. This solution was good enough for me in all practical cases and it did not require any external modules.

提交回复
热议问题