First, remember that if is evil and avoid putting anything except rewrite
or return
inside if
; a workaround suggested there is to use error_page
and return
to change location used to process the request.
As already answered here, the way to reuse location settings in nginx is to move them to a separate file and include
that file in your location
blocks.
Combining these solutions results in:
/etc/nginx/validation_code.conf
# a lot of validation code here
main config
location /location1/ {
error_page 418 = @proxy;
recursive_error_pages on;
if ($arg_api_key = a_valid_api_key) {
return 418;
}
include /etc/nginx/validation_code.conf;
}
location /location2/ {
include /etc/nginx/validation_code.conf;
}
location @proxy {
proxy_pass http://localhost:8080;
}
You may also think about using a named location for your validation code instead of creating a separate file; however, you will need some tricks to switch to that named location — e.g., another error_page
/return
pair, or something like
try_files /nonexistent @validation
/location2/...
, or keep the URL as/location1/...
and just reuse settings for/location2/
?