1

I need to perform a redirect depending on the client's IP and the value that has been set in the cookie by WPML Wordpress plugin.

I prefer to use the map directive for this purpose. Excerpt of nginx.conf

 geoip_country /usr/local/share/GeoIP/maxmind_countries.dat;
 geoip_city   /usr/local/share/GeoIP/maxmind_cities.dat;


map $host:$geoip_country_code:$cookie_wp-wpml_current_language  $redirect {
   "example.com:UA:''" "1";
   "example.com:UA:'uk'" "0";
   "example.com:UA:'ru'" "0";
}

Then in domain.conf I just check use $redirect in conditional statement

if ($redirect) {
    rewrite ^https://example.com/uk break;
}

So, my question is: how to check the value of a cookie the right way in general, and how to check if cookie is not set (has empty value) in particular using map directive for nginx?

Twissell
  • 70
  • 1
  • 11

2 Answers2

1

Configuration outlined below fits my needs

map $host $redirect_host {
    example.com 1;
    default 0;
}

map $geoip_country_code $redirect_country {
    UA 1;
    default 0;
}

map $cookie_wp-wpml_current_language $redirect_cookie {
    uk 0;
    ru 0;
    default 1;
}

map $redirect_host:$redirect_country:$redirect_cookie $make_redirect {
    1:1:1 1;
}

Then use $make_redirect variable that way in domain's configuration

if ($make_redirect) {
    rewrite ^https://example.com/uk break;
}
Twissell
  • 70
  • 1
  • 11
0

I would split the several map conditions to separate blocks:

map $host $redirect_host {
    example.com 1;
    default 0;
}

map $geoip_country $redirect_country {
    UA 1;
    default 0;
}

map $cookie_wp-wpml_current_language $redirect_cookie {
    uk 0;
    default 1;
}

Then check the conditions as follows:

if (${redirect_host}${redirect_country}${redirect_cookie} = 111) {
    return 301 https://www.example.com/uk/;
}

You need to check the defaults and conditions for each variable to match your purposes, this was just an illustration of the concept.

Tero Kilkanen
  • 34,499
  • 3
  • 38
  • 58
  • How can you combine several different variables into one? I get ```nginx: [emerg] unknown "redirect_host$redirect_country$redirect_cookie" variable nginx: configuration file /etc/nginx/nginx.conf test failed ``` while testing your solution on my side. Did you test it in practice? – Twissell Jul 19 '22 at 17:37
  • 1
    I did not test it. I added now braces around the variable names, which should fix the issue. – Tero Kilkanen Jul 19 '22 at 20:20
  • Nope, error is the same, unfortunately. But thanks for hint anyway. – Twissell Jul 19 '22 at 20:47