简体   繁体   English

如何根据Nginx中的请求URL重定向到特定的上游服务器?

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

I'm using Nginx as a load balancer for my 5 app servers. 我正在使用Nginx作为我的5个app服务器的负载均衡器。

I'd like to redirect to specific servers based on the request URL, for instance: 我想根据请求URL重定向到特定服务器,例如:

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? 我不知道怎么做,因为我对Nginx不太熟悉 - 任何人都有一些线索?

Read the documentation , eveything is well explained in it. 阅读文档 ,eveything在其中得到了很好的解释。 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;
  }

}

You will also need to rewrite the URL otherwise /whatever/ will get forwarded to the backend server 您还需要重写URL,否则/将转发到后端服务器

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM