Nginx multiple backend one server

Viewed 357

I have a server without domain name: 10.23.33.251. On this server I have two backends (spring boot): 10.23.33.251:8888/apis/a/lot/of/apis 10.23.33.251:9999/apis/a/lot/of/apis

Now I want to configure nginx to handle any request that:

/be1/employees/1?very_long_params will be proxy_pass (or proxy_redirect) to 10.23.33.251:8888/apis/employees/1?very_long_params

/be2/products/10/very/long/params will be proxy_pass (or proxy_redirect) to 10.23.33.251:9999/apis/products/10/very/long/params

But I could not make it work. Here is my configuration:

server {
    listen 8443;
    server_name localhost;

    location /be1/* {
        proxy_set_header        Host $host;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto $scheme;

        proxy_pass              http://localhost:8888/apis;
        proxy_read_timeout      90;
    }

    location /be2/* {
        proxy_set_header        Host $host;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for
        proxy_set_header        X-Forwarded-Proto $scheme;

        proxy_pass              http://localhost:9999/apis;
    }
}
1 Answers

Your locations are defined wrong. You’re trying to use a regular expression but are missing the ~ (or ~*) operator for that.

It is however not necessary to use regular expressions, you could just use prefix locations:

…
location /be1/ {
    …
}

location /be2/ {
    …
}

See also: Location Directive Documentation

Related