首页 > 解决方案 > 根据 NGINX 中的请求 URL 将请求转移到不同的服务器

问题描述

我想实现如下所示的目标,但找不到可能性:

server {
    listen 80;
    server_name localhost;

    location /get-product {
        if(request=GET){  
            proxy_pass http://get-app-server:8080/products;
            proxy_set_header Host "get-app-server";
        }
        if(request=POST){  
            proxy_pass http://post-app-server:8080/products;
            proxy_set_header Host "post-app-server";
        }
    }
}

我怎么能执行这样的决定?

标签: pythonnginxflask

解决方案


有许多可能的解决方案。例如,使用伪造的内部 URI ( /post/get-product) 来处理以下两种情况之一:

location /get-product {
    if ($request_method = POST) {
        rewrite ^ /post$uri last;
    }
    proxy_pass http://get-app-server:8080/products;
    proxy_set_header Host "get-app-server";
}
location /post/get-product {
    internal;
    proxy_pass http://post-app-server:8080/products;
    proxy_set_header Host "post-app-server";
}

请注意该if语句的正确语法和变量名称。


推荐阅读