dsollen
dsollen

Reputation: 6459

NGINX location block always redirect to different location

I have NGINX hosting many drop in apps that will usually all use the same api. My nginx has a location block for that api, so something liek

location /default-api/ {
   proxy_pass https://some/location.com;
}

Usually each GUI will want to use the same api, occasionally someone may wish to change the api a specific app uses though. I wanted each GUI to be configured to hit a different url, so that it's easier to redirect that url later if someone wants to change their api, but rather then hard coding each url to https://some/location.com in each location block I wanted to redirect to the default-api.

So effectively I want something like, if it would work

location /foo-api/ {
    redirect /default-api/; 
}

location /bar-api/ { redirect /default-api/; }

location /baz-api/ {
    redirect /default-api/; 
}

I thought when I first played with nginx that I saw a very simple directive for doing this, but I can't find it now. I know a number of directives could do this, but none of the ones I know of feel clean enough to be worth doing.

rewrite requires an overly complex regex, redirect requires the client to make a new query after getting the redirect. proxy_pass does some unneeded proxying logic, all three seem to require me to hardcode the servername into the redirect path. the cleanest I could figure out was possibly using tryfiles in a manner it wasn't made for.

Is there some simpler directive to do an internal redirect like this?

Upvotes: 2

Views: 2031

Answers (1)

Richard Smith
Richard Smith

Reputation: 49672

Two suggestions.

1) Comment out the location /foo-api block unless it is needed:

location / {
    rewrite ... ... break;   # if required to normalize the /prefix/...
    proxy_pass ...;
}
# location / foo-api/ { }    # disabled - use `location /`

2) Use a named location:

location /default-api/ {
    try_files /nonexistent @api;
}
location /foo-api/ {
    try_files /nonexistent @api;
}
location @api {
    rewrite ... ... break;   # if required to normalize the /prefix/...
    proxy_pass https://some/location.com;
}

Upvotes: 2

Related Questions