Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to specific upstream servers based on request URL in Nginx?

Tags:

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?

like image 656
CodeOverload Avatar asked Dec 01 '14 01:12

CodeOverload


People also ask

How does NGINX resolve upstream?

Upstream Domain Resolve¶ Its buffer has the latest IPs of the backend domain name and it integrates with the configured load balancing algorithm (least_conn, hash, etc) or the built in round robin if none is explicitly defined. At every interval (one second by default), it resolves the domain name.

What is upstream address in NGINX?

upstream defines a cluster that you can proxy requests to. It's commonly used for defining either a web server cluster for load balancing, or an app server cluster for routing / load balancing.


2 Answers

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

}
like image 56
Xavier Lucas Avatar answered Sep 18 '22 16:09

Xavier Lucas


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;
}
like image 38
scott Avatar answered Sep 20 '22 16:09

scott