Divert request to different server as per request-url in NGINX

Viewed 46

I want to achieve something like lined out below, but I couldn't find a possibility:

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

How could I implement such a decision?

1 Answers

There are a number of possible solutions. For example, using a fake internal URI (/post/get-product) to handle one of the two cases:

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

Note the correct syntax and variable name for the if statement.

Related