Nginx routing to several RESTful endpoints
Asked Answered
D

1

7

I would like to use Nginx as the HTTP proxy server.

On the backend, we have 3 different applications written in Java exposing a RESTful API each. Every application has their own prefix on the API.

For instance:

APP 1 - URI prefix: /api/admin/**
APP 2 - URI prefix: /api/customer/**
APP 3 - URI prefix: /api/support/**

On the frontend, we have a SPA page making requests to those URI's.

Is there a way to tell Nginx to route the HTTP request depending on the URI prefix?

Thanks in advance!

Disavow answered 14/6, 2016 at 18:55 Comment(0)
S
13

I am pretty sure you can use nginx proxy forwarding to re-route according to each of your several uri prefixes. I have used proxy forwarding with nginx. Your example I have adapted from a page that gives information specifically on uri prefixes (I have preserved the /foo entry from that page here for your comparison):

https://serverfault.com/questions/379675/nginx-reverse-proxy-url-rewrite

See also (noting difference of proxy_pass from proxy_redirect), http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

With your code, the locations would be something like:

server {
listen          80;
server_name     www.example.com;

location /api/admin {
  proxy_pass http://localhost:3200/;
}

location /api/customer {
  proxy_pass http://localhost:3200/;
}

location /api/support {
  proxy_pass http://localhost:3200/;
}

location /foo {
  proxy_pass http://localhost:3200/;
}

}

As the link I have provided mentions, note the forward slash at the end of each location directive that enables the wild carding after the prefix. And of course the urls to which each of the paths are redirected need not all be the same--localhost:3200--as they are in this example.

Sisley answered 14/6, 2016 at 19:28 Comment(2)
Awesome! Thanks! This is what I was looking for :)Disavow
Thanks @benWeaver, this lead me down a path that solved my somewhat related issue.Whitmer

© 2022 - 2024 — McMap. All rights reserved.