Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am trying to achieve something like this:

location /location1/{
    if ($arg_api_key = a_valid_api_key) {
         proxy_pass http://localhost:8080;
    }
    # else jump to location2
}
location /location2/{
    # a lot of validation code here
}

How do we do it in nginx? Or is there a better way handling it?

share|improve this question

closed as not a real question by mdpc, mgorven, Tim Brigham, Ward, Tom O'Connor May 21 '13 at 13:16

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

    
What do you mean by “jump” — rewrite the URL to /location2/..., or keep the URL as /location1/... and just reuse settings for /location2/? –  Sergey Vlasov May 20 '13 at 17:54
    
the second one: keep the URL as /location1/... and just reuse settings for /location2/ –  Winston Chen May 20 '13 at 18:01
    
What are you really trying to do? –  Michael Hampton May 20 '13 at 22:26

1 Answer 1

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
share|improve this answer
    
error_page 418 = @proxy; -> It works for me. However, all the parameters are lost. Is there a way to do it with all the parameters? –  Winston Chen May 20 '13 at 21:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.