How to redirect to specific upstream servers based

2020-06-01 01:58发布

问题:

I'm using Nginx as a load balancer for my 5 app servers.

I'd like to redirect to specific servers based on the request URL, for instance:

acme.com/category/*          => Server #1
acme.com/admin/*             => Server #2
api.acme.com                 => Server #3
Fallback for any other URL   => Server #4, #5

My config looks like:

upstream backend  {
  least_conn;
  server 10.128.1.1;
  server 10.128.1.2;
  server 10.128.1.3;
  server 10.128.1.4;
  server 10.128.1.5;
}

server {
  listen 80;
  server_name _;

  location / {
    proxy_set_header Host $host;
    proxy_pass  http://backend;
  }
}

I have no idea how to do this, since I'm not very familiar with Nginx - any one has some clues?

回答1:

Read the documentation, eveything is well explained in it. There's particularly a beginner's guide explaining basics. You would end up with :

upstream backend  {
  least_conn;
  server 10.128.1.4;
  server 10.128.1.5;
}

server {

  server_name _;

  location / {
    proxy_set_header Host $host;
    proxy_pass  http://backend;
  }

}

server {

  server_name acme.com;

  location /admin/ {
    proxy_set_header Host $host;
    proxy_pass  http://10.128.1.2;
  }

  location /category/ {
    proxy_set_header Host $host;
    proxy_pass  http://10.128.1.1;
  }

  location / {
    proxy_set_header Host $host;
    proxy_pass  http://backend;
  }

}

server {

  server_name api.acme.com;

  location / {
    proxy_set_header Host $host;
    proxy_pass  http://10.128.1.3;
  }

}


回答2:

You will also need to rewrite the URL otherwise /whatever/ will get forwarded to the backend server

location /admin/ {
    rewrite ^/admin^/ /$1 break;
    proxy_pass http://10.128.1.2;
}


标签: nginx