Nginx 重写proxy_pass的URL代理到不同主机
需求背景,前端访问一个域名以URL区分代理到哪个后端服务,同时后端URL不包含这个匹配的URL
栗子:访问http://api.example.com/npt/users/info,其中 /npt 作为区分URL,后端user服务的URL只有/users/info,因此proxy_pass前就得先把URL的 /npt 给重写掉才能匹配到后端服务,下面是具体栗子代码
server {
listen 80;
server_name aa.com;
location /npt {
rewrite ^/npt/(.*) /$1 break;
proxy_pass http://localhost:8080;
access_log /home/npt.access.log json;
error_log /home/npt.error.log;
}
location /apt {
rewrite ^/apt/(.*) /$1 break;
proxy_pass http://localhost:9090;
access_log /home/apt.access.log json;
error_log /home/apt.error.log;
}
}
server {
listen 8080;
server_name _;
location / {
default_type text/html;
return 200 'This is domain 8080 index text!';
}
location /abc {
default_type text/html;
return 200 'This is domain 8080 URL=/abc text!';
}
location /qwe {
default_type text/html;
return 200 'This is domain 8080 URL=/qwe text!';
}
}
server {
listen 9090;
server_name _;
location / {
default_type text/html;
return 200 'This is domain 9090 index text!';
}
location /abc {
default_type text/html;
return 200 'This is domain 9090 URL=/abc text!';
}
}