Search code examples
nginxhttp-redirectnginx-config

nginx conf file: Detect if browser language is "de", then redirect to page .... else redirect to other page


I want to create a link in a banner to redirect to one of two pages. The link points to subdomain.example.com/email. If the browser language is "de" then go to www.example.de/banner else go to www.example.com/banner. My nginx conf language skills are not good, but I know that any browser language of German has the first two characters are "de" (see https://www.metamodpro.com/browser-language-codes). No other language has this.

location /email {
    if $http_accept_language === "de" { return 301 https://www.example.de/banner }
    else { return 301 https://www.example.com/banner}
}

Solution

  • A cleaner and extensible solution uses the map directive.

    For example:

    map $http_accept_language $redirect {
        default    https://www.example.com/banner;
        ~de        https://www.example.de/banner;
    }
    
    server {
        ...
        location /email {
            return 301 $redirect;
        }
        ...
    }
    

    See this document for details.