Score:0

Understanding Return in nginx

tr flag

I have a configuration file with a config similar to the below

map $request_uri $redirectWithError {
  default "0"
  "~* /<uri>" "1"
}

location / {
 if ($redirectWithError = "1") {
   return 404;
 }
 
 location / {
   proxy_pass <another_address>
 }

 location /search {
   proxy_pass <another_address>
 }
}


My assumption was that when the condition in the "if statement" is true then we would return 404 error and the location blocks which contain proxy_pass wouldn't be executed. But from what I have tested and observed this is not the case. Even after the if statement is executed the location blocks are also getting executed.

Is there a way to avoid the location blocks here ? i.e., if the "if conditions is true" then return 404 else check for within the location blocks.

PS: I have gone through this how-nginx-location-if-works and If is evil to understand the inner workings of the if statements. But I wasn't able to find any blog which specifies how the return works

Richard Smith avatar
jp flag
Why are you placing the `if` block inside a `location`? Place the `if` block in `server` context and it will be evaluated **before** any location is selected to process the request.
Score:1
br flag

Why do you want to use if to check URI? That's what location is for.

location / {
  proxy_pass <another_address>;
}

location /search {
  proxy_pass <another_address>;
}

location ~* /<uri> {
  return 404;
}

https://nginx.org/r/location

I sit in a Tesla and translated this thread with Ai:

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.