大网数据广告活动
服务器运维问答

Check HTTP cookie value with nginx using map directive

· 52CE 我爱测

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/…

问题原文

原帖链接 · Twissell · CC BY-SA 4.0

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 · CC BY-SA 4.0

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;
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2022-07-16)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。