网络应用服务器-Nginx系列

Nginx配置location进行接口转发

2020-09-07  本文已影响0人  AbstractCulture

需求描述

story

使用Nginx配置location进行接口转发

生产环境中,用户首先访问网站的域名,然后由Nginx监听80端口对请求进行转发。

例如用户发起以下请求查询汇率数据:
http://[WEB_DOMAIN]/api/v1/runtime/exchange
经过Nginx处理后到达服务端的请求则是这样的:
http://[host:port]/v1/runtime/exchange
这个请求再经过微服务的网关,找到runtime服务,就会访问路由为/exchange的接口。
了解了这个后,我们来处理需求。

约定

跟coupons服务接口侧商定,所有关于coupons服务的接口均采用applcationCodecoupons参数进行路由映射.
举个例子:该服务部署在192.168.31.2下的8085端口,提供了一个查询接口,那么应该是这种规则:

http://192.168.31.2:8085/runtime/coupons/data

此时,前端依然保持系统原有风格进行api调用:

http://www.baidu.com/api/v1/runtime/coupons/data

那么如何实现访问http://www.baidu.com/api/v1/runtime/coupons/data跳转到http://192.168.31.2:8085/runtime/coupons/data呢?

Nginx配置:

index  index.html index.htm;
proxy_connect_timeout 3000s;
proxy_send_timeout 3000s;
proxy_read_timeout 3000s;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
client_max_body_size    100m;
server
{
    ## 监听80端口
    listen 80;
    ## 访问域名 WEB_DOMAIN为具体的域名,如:www.baidu.com
    server_name WEB_DOMAIN;
    index index.html index.htm;
    ## 匹配 路径中包含 /api/v1 的请求,并且/api/v1/后存在runtime或者workbench,将这些请求转发到具体的proxy_pass中
    location ~ ^/api/v1/(runtime|workbench)/coupons/ {
        ## 引入proxy_params文件的配置信息
        include    proxy_params;
        ## 代理转发地址,具体的 host 和 post 自己指定
        proxy_pass http://host:port;
        ## 重写,转发前,将url中的某些参数进行过滤
        rewrite ^/api/v1/(.*)$ /$1 break;
    }
    ## 日志
    access_log logs/*.log;
}
shell> cd sbin
shell> ./nginx -s reload

这样,就可以使用nginx对coupons服务接口进行转发了

上一篇下一篇

猜你喜欢

热点阅读