4

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?

3
  • What do you mean by “jump” — rewrite the URL to /location2/..., or keep the URL as /location1/... and just reuse settings for /location2/? May 20, 2013 at 17:54
  • the second one: keep the URL as /location1/... and just reuse settings for /location2/ May 20, 2013 at 18:01
  • What are you really trying to do? May 20, 2013 at 22:26

1 Answer 1

6

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
1
  • 2
    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? May 20, 2013 at 21:19

Not the answer you're looking for? Browse other questions tagged .