nginx geotargeting and proxpass

Tomcat666 asked:

I have a little issue with my Nginx config prototype

The Scenario is following: website visitor will visit example.com. Nginx is read out with GeoIP the current location and accept language header from a browser.

this information must be referring to proxypass

My issue is, how to tell Nginx to use the proxypass with this two variables.
With this configuration, I become a 404 error.

any idea?

geoip_country   /usr/share/GeoIP/GeoIP.dat;
geoip_proxy 10.241.16.0/24; 



upstream hybrisqa {
       server qa-hybris.local:9001;
}



server {
    listen 80 default_server;
    listen [::]:80 default_server;
#   root /var/www/html;
allow all;
    access_log  /var/log/nginx/test_access.log;
    error_log  /var/log/nginx/test.error.log;



    # Add index.php to the list if you are using PHP
#   index index.html index.htm index.nginx-debian.html;

    server_name   _;

#        return 301 /$geoip_country_code;




location = / {

          rewrite_by_lua '
           if (ngx.var.http_accept_language == nil or ngx.var.http_accept_language == "") then
            ngx.redirect("/en-" .. ngx.var.geoip_country_code .. "/")
          end
          for lang in (ngx.var.http_accept_language .. ","):gmatch("([^,]*),") do
          if string.sub(lang, 0, 2) == "en" then
          ngx.redirect("/en-" .. ngx.var.geoip_country_code .. "/" )
          end
          if string.sub(lang, 0, 2) == "de" then
          ngx.redirect("/de-" .. ngx.var.geoip_country_code .. "/" )
          end
          if string.sub(lang, 0, 2) == "nl" then
          ngx.redirect("/nl-" .. ngx.var.geoip_country_code .. "/"  )
          end
          end
          ngx.redirect("/en-US/")
          ';

}


location / {

 proxy_pass http://hybrisqa;


try_files $uri $uri/ =404;


}

}

My answer:


Lua is too much complexity for this. It’s easiest to use a map.

Note that one little-known property of maps is that they can check several variables at once, by concatenating them.

For example:

map $geoip_country_code$http_accept_language $locale {
    default en-US
    ~^DEde  de-DE
    ~^NLnl  nl-NL
    # ... continue for every supported combination of language and country
}

server {
    location = / {
        return 302 /$locale/;
    }
    # ....

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.