how to create session persistence or hash_ip within server context for an if statement

Jelle de Jong jelledejong at powercraft.nl
Mon Jan 24 15:09:34 UTC 2022


On 1/24/22 11:15, Reinis Rozitis wrote:
>> I want to be able to do an redirect, but only one time, the hit it should
> not redirect.
>>
>> If a client visits an web-store it will get redirected to the region
> specific store, but if then then manually select an other store there it
> should not redirect back again. I don't know if a nginx session cookie is
> possible or an way to use the nginx upstream module?
> 
> If your website uses cookies (and sets some information you can identify a
> region) one way would be to make a decision on that - nginx can access
> cookies using $cookie_COOKIENAME variable(s) so you can add it as an if() or
> map conditions to decide if a redirect is needed.

I got it working! I am not sure of the performance hit, maybe someone 
know how to make this more effective?

I noticed that the if statements have an higher priority then the 
location sections and it does not follow the order in the configuration 
file. I needed an additional if statement to check the request URL...

if ($cookie_REDIRECT != false) {
	set $redirect true;
}
if ($request_uri ~ "^/(noredirect)/(.*)$" ) {
	set $redirect false;
}
location ~ ^/(noredirect)/ {
	add_header Set-Cookie 
"REDIRECT=false;Domain=$host;Path=/;Max-Age=31536000";
	rewrite ^/noredirect(.*)$ https://$host$1 redirect;
}
if ($geoip2_data_country_iso_code = IE) {
	set $redirect ${redirect}+test02.example.nl;
}
if ($redirect = true+test02.example.nl) {
	return 302 https://test02.example.nl$request_uri;
}
if ($geoip2_data_country_iso_code != GB) {
	set $redirect ${redirect}+test03.example.nl;
}
if ($redirect = true+test03.example.nl) {
	return 302 https://test03.example.nl$request_uri;
}

if ($geoip2_data_country_iso_code = NL) {
	set $MAGE_RUN_CODE_ORG storeview07;
}
if ($geoip2_data_country_iso_code = US) {
	set $MAGE_RUN_CODE_ORG storeview08;
}
if ($geoip2_data_country_iso_code = DE) {
	set $MAGE_RUN_CODE_ORG storeview09;
}
location / {
	proxy_pass http://127.0.0.1:6081;
	add_header Strict-Transport-Security "max-age=31536000; 
includeSubDomains" always;
}

If I am falling in a pitfall somehow let me know, it seems to work well.

Kind regards,

Jelle



More information about the nginx mailing list