nginx配置二级目录,反向代理不同ip+端口

场景描述:

通过二级目录(虚拟目录,应用程序)的方式访问同一ip+端口的不同应用,例如location是用户使用页面,location/admin/是管理页面,location部署在192.168.1.100的80端口,location/admin部署在172.20.1.32的8080端口上。

解决方案:

使用nginx反向代理,配置如下:

server {
listen 80;
server_name demo.domain.com;
#通过访问service二级目录来访问后台
location /service {
#DemoBackend1后面的斜杠是一个关键,没有斜杠的话就会传递service到后端节点导致404
proxy_pass http://DemoBackend1/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#其他路径默认访问前台网站
location / {
proxy_pass http://DemoBackend2;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

#简单的负载均衡节点配置
upstream DemoBackend1 {
server 192.168.1.1;
server 192.168.1.2;
ip_hash;
}
upstream DemoBackend2 {
server 192.168.2.1;
server 192.168.2.2;
ip_hash;
}

但是这种方式,二级目录的样式文件都不会正常显示,他们不会自动在二级目录下查找,而是在根目录中查找,在跳转页面的时候也会报404错误。不知道是不是配置有误,在server块中配置了root或是rewrite都不能解决。

试着在proxy_pass后面加上二级目录,并且和location块的二级目录相同,配置如下:

server {
listen 80;
server_name demo.domain.com;
#通过访问service二级目录来访问后台
location /service {
#DemoBackend1后面的斜杠是一个关键,没有斜杠的话就会传递service到后端节点导致404
proxy_pass http://DemoBackend1/service;#DemoBackend1网站中要配置一个名称为service的虚拟目录,并且和location的二级目录名称一致
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
#其他路径默认访问前台网站
location / {
proxy_pass http://DemoBackend2;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

#简单的负载均衡节点配置
upstream DemoBackend1 {
server 192.168.1.1;
server 192.168.1.2;
ip_hash;
}
upstream DemoBackend2 {
server 192.168.2.1;
server 192.168.2.2;
ip_hash;
}

问题解决

另外,在实际应用中,我使用了asp.net 的mvc,将mvc设置为网站的方式没有问题,如果是虚拟目录的方式就会找不到路径,是因为自己在网站中的地址很多写的都不规范,正确的方式应该是:

Here's a typical example of what you should never do:


and here's how this should be done:


Here's another typical example of something that you should never do:

Foo

and here's how this should be written:

@Html.ActionLink("Foo", "Index", "Home")

Here's another example of something that you should never do:

and here's how this should be written:

@using (Html.BeginForm("Index", "Home"))
{

}


引用:
https://zhangge.net/5054.html
http://blog.csdn.net/lusyoe/article/details/52928649

转载于:https://www.cnblogs.com/bayu/p/8041453.html


🐞标题:nginx配置二级目录,反向代理不同ip+端口
👽作者:ruige
🐾地址:https://jjdhhc.com/articles/2020/08/19/1597835946283.html
🙏感恩:谢谢您的打赏与支持!中间图片是我的微信公众号,扫码关注哦!
支付宝支付 微信公众号 微信支付