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

I use Nginx as a load balancer for 5 application servers.

I would like to redirect to specific servers based on the request URL, for example:

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 is as follows:

 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 do not know how to do this, since I am not very familiar with Nginx - does anyone have any hints?

+6
source share
2 answers

Read the documentation , it is well explained. In particular, the beginner's guide explains the basics. As a result, you will receive:

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

You will also need to rewrite the URL otherwise / whatever / will be redirected to the server server

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

Source: https://habr.com/ru/post/978917/


All Articles