1. 版本:nginx-1.24.0 ,windows 10 64bit,22H2 19045.4529
2. 需求:使用一个nginx反向代理多个系统的内网服务,例如有两个系统,分别为sys1,sys2,物理机的ip分别为192.168.10.125以及192.168.10.67,nginx配置如下:
upstream sys1Service{server 192.168.10.125:8888;}upstream sys2Service{server 192.168.10.67:8888;}upstream sys1Handle{server 127.0.0.1:8881;}upstream sys2Handle{server 127.0.0.1:8882;}server {listen 8881;server_name sys1;location / {# root html;# index index.html index.htm;# 这里还可以根据请求的方法名,转发给不同的主机if ( $request_uri = "/methodName1" ){proxy_pass http://sys1Service;}if ( $request_uri = "/methodName2" ){proxy_pass http://sys1Service;}}}server {listen 8882;server_name sys2;location / {# root html;# index index.html index.htm;if ( $request_uri = "/methodName1" ){proxy_pass http://sys2Service;}if ( $request_uri = "/methodName2" ){proxy_pass http://sys2Service;}}}server {listen 80;server_name localhost;location / {root html;index index.html index.htm;}}server {listen 8880;server_name localhost;#charset koi8-r;#access_log logs/host.access.log main;location / {root html;index index.html index.htm;}location /sys1/ {#root html;#index index.html index.htm;#rewrite ^/sys1(.*)$ /$1 permanent;# 替换 rewrite ^/old_part(.*)$ /new_part$1 break;#添加 rewrite ^/(.*)$ /new_prefix/$1 last;rewrite ^/sys1(.*)$ $1 break;proxy_set_header Host $http_host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header REMOTE-HOST $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#全部交给sys1Handle处理proxy_pass http://sys1Handle;}location /sys2/ {#root html;#index index.html index.htm;#rewrite ^/sys2(.*)$ /$1 permanent;# 替换 rewrite ^/old_part(.*)$ /new_part$1 break;#添加 rewrite ^/(.*)$ /new_prefix/$1 last;rewrite ^/sys2(.*)$ $1 break;proxy_set_header Host $http_host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header REMOTE-HOST $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#全部交给sys2Handle处理proxy_pass http://sys2Handle;}
假设外网访问nginx的域名是fake-domain,对系统1的访问是:http://fake-domain/sys1/方法名,对系统2的访问是:http://fake-domain/sys2/方法名;
当客户端请求 http://fake-domain/sys1/methodName1时,nginx先转发给自己,然后再转发给目标服务机,服务机编写服务时,只需要路由methodName1即可。