根据 http_cookie 首选项的国家代码重写到 Nginx 上的适当站点

Based on country code of http_cookie preference rewrite to the appropriate sites on Nginx

如何根据最终用户偏好的cookies进行路由? 我们有 Nginx/1.17.10 运行 作为 AKS 中的 pod。电子商务网站托管于此。 CloudFlare 是充当 DNS 和 WAF 的前端。 CloudFlare 启用了 GeoIP,所以我们有参数 - $http_cf_ipcountry 来跟踪国家代码。然而,我们正在寻找最终用户保存的偏好并路由到该特定区域。

示例:

If $http_cookie --> COUNTRY_CODE=UAE;
Then rewrite to example.com --> example.com/en-ae
If $http_cookie --> COUNTRY_CODE=KW;
Then rewrite to example.com --> example.com/en-kw
If there is no preference saved on cookie, then route to default "example.com"

Http_cookie 参数还包含其他详细信息,例如 _cfduid、COUNTRY_CODE_PREV、CURRENYCY_CODE、EXCHANGE_RATE

处理此要求的最佳方法应该是什么? 任何人都可以帮助我,谢谢!

我会创建一个映射来处理重定向 URL 的构建。 http://nginx.org/en/docs/http/ngx_http_map_module.html#map

这会将重写 url 设置为变量 $new_uri。如果没有 cookie 值,则默认值为 /en-en/。现在您可以创建重写规则了。

 rewrite ^(.*)$ $new_uri permanent;

这是根据要求更新的配置示例。

map $cookie_user_country $new_uri {
    default /en-en/;
    UAE /en-ae/;
    KW /en-kw/;
}


server {
        listen 8080;
        return 200 "$uri \n";
}

server {
        listen 8081;
        rewrite ^(.*)$ $new_uri permanent;
        return 200 "$cookie_user_country \n";
}

使用 $cookie_NAME 指令获取单个 cookie 的正确值。 $http_VAR 包含特定 HTTP 请求的值 header。

查看我的 curl 请求了解更多详情。

[root@localhost conf.d]# curl -v --cookie "user_country=KW; test=id; abcc=def" localhost:8081
* About to connect() to localhost port 8081 (#0)
*   Trying ::1...
* Connection refused
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8081 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:8081
> Accept: */*
> Cookie: user_country=KW; test=id; abcc=def
>
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.17.6
< Date: Sun, 26 Apr 2020 12:34:15 GMT
< Content-Type: text/html
< Content-Length: 169
< Location: http://localhost:8081/en-kw/
< Connection: keep-alive
<
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.17.6</center>
</body>
</html>
* Connection #0 to host localhost left intact

正在检查当前 运行 NGINX 二进制文件包含映射模块

类型

strings `which nginx` | grep ngx_http_map_module | head -1

这将列出 nginx 二进制文件中的所有 "printable" 字符串,并通过 "ngx_http_map_module" grep 输出。结果应如下所示:

[root@localhost conf.d]# strings `which nginx` | grep ngx_http_map_module | head -1

--> ngx_http_map_module

如果输出与 ngx_http_map_module 相等,则当前的 运行 NGINX 二进制文件是使用地图支持编译的。如果不是 -> 请确保您使用的是编译后支持地图的 NGX 二进制文件。