0

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

  • 2
    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. – Richard Smith Aug 22 '23 at 07:14

1 Answers1

1

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

Alexey Ten
  • 8,435
  • 1
  • 34
  • 36