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

前端 未结 10 1938
爱一瞬间的悲伤
爱一瞬间的悲伤 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:51

    Okay, I've had the same problem and "misuse" Lua to make a redirect possible based on the browser language.

    # Use Lua for HTTP redirect so the site works
    # without the proxy backend.
    location = / {
        rewrite_by_lua '
            for lang in (ngx.var.http_accept_language .. ","):gmatch("([^,]*),") do
                if string.sub(lang, 0, 2) == "en" then
                    ngx.redirect("/en/index.html")
                end
                if string.sub(lang, 0, 2) == "nl" then
                    ngx.redirect("/nl/index.html")
                end
                if string.sub(lang, 0, 2) == "de" then
                    ngx.redirect("/de/index.html")
                end
            end
            ngx.redirect("/en/index.html")
        ';
    }
    

    Note: NGINx needs to have liblua compiled to it. For Debian/Ubuntu:

    apt-get install nginx-extras
    

提交回复
热议问题