Redirect loop with try_files

Hi,

I have a front end nginx webserver with behind it a tomcat server. I ran
into a nasty little redirect loop issue that I still don’t understand.
I’m
trying to redirect users who have a session cookie to a different page
than
the other users

I have a configuration such as this:

Rewrite index requests

rewrite ^(.)/index.(.)$ $1/ permanent;

map $cookie_msa_country $ctry {
default 0;
NL “nederland/NL_”;
BR “brasil/BR_”;
}

map $cookie_msa_lng $lng {
default “nl”;
nl “nl”;
pt “pt”;
es “es”;
en “en”;
}
location = / {
set $red 0;
if ($http_cookie ~* “JSESSIONID”){
set $red 1;
}
if ($ctry = 0){
set $red 0;
}
if ($red = 1){
rewrite ^(.*)$ http://$host/$ctry$lng/account/wall/;
}

 try_files /notthere.html @proxy;

}

When a users types in domain www.site.com, he ends up in an endless
loop. I
tried various things but without luck. Any suggestions how to avoid
this?

Posted at Nginx Forum:
http://forum.nginx.org/read.php?2,238837,238837#msg-238837

On Sat, May 04, 2013 at 10:20:32AM -0400, mschipperheyn wrote:

Hi there,

Rewrite index requests

rewrite ^(.)/index.(.)$ $1/ permanent;

That is likely to lead to a loop, unless you take great care elsewhere.

(The typical defaults are: a request for /dir/ leads to an internal
rewrite to /dir/index.html, which the above would convert to an external
redirect to /dir/, which is where we came in.)

location = / {
set $red 0;
if ($http_cookie ~* “JSESSIONID”){
set $red 1;
}

Here, you use “if” inside “location” and you do something other than
“return” or “rewrite … last”. That’s rarely a good idea:

http://wiki.nginx.org/IfIsEvil

Can you move the if/set logic to server{} level, to avoid that likely
confusion?

When a users types in domain www.site.com, he ends up in an endless loop.

I strongly suspect that the loop is caused by the first rewrite, because
the try_files does not apply because at least one of your “if”
conditions
is true.

You can test that by trying “curl -i http://www.site.com/”, and adding
whatever is necessary to make sure that none of the “if” conditions
match,
and seeing if you get anything different.

Or you can just redo the configuration to avoid most “if” inside
“location” blocks.

f

Francis D. [email protected]