How to route based on cookies preferred by the end user? We have Nginx/1.17.10 running as pod in AKS. eCommerce site is hosted on this. CloudFlare is front end acting as DNS and WAF. CloudFlare have GeoIP turned on , so we have parameter - $http_cf_ipcountry to trace the country code. however we are looking for the preference saved by end user and route to that specific region.
Example:
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 parameter also holds other detail such as _cfduid, COUNTRY_CODE_PREV, CURRENYCY_CODE , EXCHANGE_RATE
What should be the best approach to handle this requirement? Anyone help me on this, thanks!
I would create a map to handle construct the redirect URLs. http://nginx.org/en/docs/http/ngx_http_map_module.html#map
This will set the rewrite url to a variable $new_uri. The default, if no cookie value is present, will be /en-en/. Now you can create a rewrite rule.
rewrite ^(.*)$ $new_uri permanent;
Here is an updated config example as requested.
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";
}
Use the $cookie_NAME directive to get the right value of a single cookie. The $http_VAR contains the value of a specific HTTP request header.
See my curl request for more details.
[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
type
strings `which nginx` | grep ngx_http_map_module | head -1
This will list all "printable" strings from the nginx binary and grep the output by "ngx_http_map_module". The result should look like this:
[root@localhost conf.d]# strings `which nginx` | grep ngx_http_map_module | head -1
--> ngx_http_map_module
If the output is eq to ngx_http_map_module the current running NGINX binary was compiled with map support. If not -> make sure you are using a NGX Binary compiled with map support.