一:用nginx做反向代理

为了解决这两个问题,自然第一反应想到的就是使用反向代理,我的理想构思下应该是下图这样的。


既用户所有的请求都经过nginx,让nginx来判断当前url需要跳转到哪一个后端代理上,比较好的策略应该是让nginx来判断当前的host是什么来决定跳转到后端的哪一个webserver上,比如a.mip.com 就跳转到apollo,j.mip.com 就跳转到jenkins. 以此类推,这样就可以完美解决了,是吧? 在nginx中你完全可以使用rewrite模块下if指令来进行判断。


二:使用if指令

这里要提一下,nginx比较原始化,如果需使用第三方module,你还需要重新编译nginx,用起来很麻烦,所以这里干脆使用OpenResty,它扩展了nginx,并且集成了很多成熟的lua模块,自行下载最新的1.15.8,安装方式和nginx一模一样。


默认是安装到/usr/local/目录下,当你看到有一个openresty目录表示你安装成功。

[root@localhostlocal]#lsbinetcgamesincludeliblib64libexecopenrestysbinsharesrc[root@localhostlocal]#pwd/usr/local

接下来你可以使用 nginx -v 来看一下openresty版本号啥的。

[root@localhostsbin]#pwd/usr/local/openresty/nginx/sbin[root@localhostsbin]#[root@localhostsbin]#./nginx-vnginxversion:openresty/1.15.8.1

为了方便,我就直接使用nginx开启三个server:

<1> 192.168.23.129:80   nginx上开启的第一个网站,就是proxy了。

<2> 192.168.23.129:8001 nginx上开启的第二个网站,模拟apollo。

<3> 192.168.23.129:8002 nginx上开启的第三个网站,模拟jenkins。


1. apollo的模拟:

server{listen8001;server_namesomenamealiasanother.alias;location/{roothtml;indexapollo.html;}}

8001端口网站的默认页是apollo.html,这个apollo.html所在路径就是在nginx下的html目录,如下所示。

[root@localhosthtml]#pwd/usr/local/openresty/nginx/html[root@localhosthtml]#ls50x.htmlapollo.htmlindex.htmljenkins.html

2. jenkins的模拟

server{listen8002;server_namesomenamealiasanother.alias;location/{roothtml;indexjenkins.html;}}

jenkins.html的文件所在路径如上所示哈。不再赘述。

3. proxy的模拟


可以看到,只需要使用rewrite模块下的if条件语句,通过$host系统变量判断当前的url中的host的值跳转到相应的网站。


4. host映射

好了,接下来只需要将a.mip.com 和 j.mip.com 映射到nginx的ip地址192.168.23.129即可。因为这些域名方便记忆而不是真实存在的。

192.168.23.129a.mip.com192.168.23.129j.mip.com


5. 启动nginx

[root@localhostsbin]#./nginx[root@localhostsbin]#[root@localhostsbin]#[root@localhostsbin]#netstat-tlnpActiveInternetconnections(onlyservers)ProtoRecv-QSend-QLocalAddressForeignAddressStatePID/Programnametcp000.0.0.0:80010.0.0.0:*LISTEN3802/nginx:mastertcp000.0.0.0:80020.0.0.0:*LISTEN3802/nginx:mastertcp000.0.0.0:800.0.0.0:*LISTEN3802/nginx:mastertcp000.0.0.0:220.0.0.0:*LISTEN1172/sshdtcp00127.0.0.1:250.0.0.0:*LISTEN1724/mastertcp600:::22:::*LISTEN1172/sshdtcp600::1:25:::*LISTEN1724/master

通过上图可以看到,80,8001,8002 端口都已经开启了,接下来大家可以到浏览器去验证一下了。




可以看到这个问题已经很完美的解决了,好了,这就是本篇和大家聊到的实际场景中遇到的一个问题,希望本篇对你有帮助。