Score:1

Nginx rewrite and return interfere with different location block

cn flag

I have the following configuration in nginx for redirecting in a certain scenario.

location /prefix-someurl {
   if (condition) {
            return 301 $scheme://$host/xyz.html;
   }
   proxy_pass someValue;
}

and in another block there are some rewrite rules like this

location /someurl {
   if (condition) {
            rewrite ^(.*)abc(.*)$ $1test/abc$2 break;               
            rewrite ^(.*)someurl/$(.*) $1someurl/test/index.html$2;

   }
   proxy_pass value;
}

The above configuration works as intended. However if for the latter I make this modification;

location /someurl {
   if (condition) {
            return 301 $scheme://$host/xyz.html;
   }
   if (condition) {
            rewrite ^(.*)abc(.*)$ $1test/abc$2 break;               
            rewrite ^(.*)someurl/$(.*) $1someurl/test/index.html$2;

   }
   proxy_pass value;
}

I get too many redirect errors for accessing /prefix-someurl.If I modify the /someurl to the following the error goes away;

location /someurl {
  if (condition) {
        return 301 $scheme://$host/xyz.html;
  }    
  proxy_pass value;
}

I cannot understand why modifying /someurl has an impact on /prefix-someurl. Or am I missing something regarding nginx rewrite evaluation. Insight on this would be appreciated.

Richard Smith avatar
jp flag
You need to identify each step in the loop. Use `curl -I` to test the individual redirects. Also, enable the [`rewrite_log`](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite_log) to get diagnostics from the rewrite engine.
us flag
You can most likely find an answer at https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/ . Instead of `if`, you should use `map` and use another strategy for your conditions.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.