Nginx路由到几个RESTful端点

时间:2016-06-14 18:55:53

标签: rest http nginx routing http-proxy

我想使用Nginx作为HTTP代理服务器。

在后端,我们有3个用Java编写的不同应用程序,每个应用程序都暴露一个RESTful API。每个应用程序在API上都有自己的前缀。

例如:

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

在前端,我们有一个SPA页面向这些URI发出请求。

有没有办法告诉Nginx根据URI前缀路由HTTP请求?

提前致谢!

1 个答案:

答案 0 :(得分:6)

我很确定您可以使用nginx代理转发根据您的几个uri前缀重新路由。我使用nginx代理转发。您的示例我改编自一个页面,该页面提供了有关uri前缀的信息(我在此处保留了该页面的/ foo条目以供您比较):

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

另请参阅(注意proxy_pass与proxy_redirect的区别), http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass

使用您的代码,位置将类似于:

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/;
}

}

作为我提到的链接,请注意每个位置指令末尾的正斜杠,它在前缀后启用野性梳理。当然,每个路径被重定向到的URL都不需要全部相同 - localhost:3200 - 就像它们在这个例子中一样。