1. 程式人生 > >nginx 配置多域名 及 tomcat 負載均衡 二

nginx 配置多域名 及 tomcat 負載均衡 二

上回建立了 test.tomcat.com —— nginx —— 8080 8081

缺點在於

1 nginx負載均衡部署的 127.0.0.1:8080 和 127.0.0.1:8081 訪問各自的webapp目錄,給war包的部署帶來麻煩,需要部署兩臺tomcat

2 如果不僅有test.tomcat.com 還有其他二級域名 如 test1.tomcat.com 等域名需要訪問不同的應用則不太方便

先解決第一個問題,那麼就需要將兩臺tomcat host 指向同一個目錄:

      <Host name="localhost"  appBase="D:\nginx-1.12.0\html\tomcat_localhost"
            unpackWARs="true" autoDeploy="true">
<Context path="" docBase="D:\nginx-1.12.0\html\tomcat_localhost" debug="0" reloadable="false" crossContext="true"/>   這一句是加的,否則無法訪問
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="localhost_access_log" suffix=".txt" pattern="%h %l %u %t "%r" %s %b" /> </Host>

我們在nginx的html中將tomcat主頁複製過去,目錄為:tomcat_localhost   然後在index.jsp中標明 localhost

重啟兩臺tomcat,訪問 test.tomcat.com

ok,此時兩臺伺服器同時指向 D:\nginx-1.12.0\html\tomcat_localhost,我們設定的旗標處顯示 localhost 而不再是交替顯示 local 8080 和 local 8081


第二個問題,涉及到tomcat 虛擬主機

為了區別,在nginx的html中將tomcat主頁複製過去,目錄為tomcat_test.tomcat.com ,然後在index.jsp中標明 test.tomcat.com

在兩臺tomcat server.xml中加入,配置虛擬主機

<Host name="test.tomcat.com" appBase="D:\nginx-1.12.0\html\tomcat_test.tomcat.com" unpackWARs="true" autoDeploy="true">
  <Context path="" docBase="D:\nginx-1.12.0\html\tomcat_test.tomcat.com" debug="0" reloadable="false" crossContext="true"/>
  <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
    prefix="test.tomcat.com." suffix=".txt" pattern="%h %l %u %t "%r" %s %b" />
</Host>

重啟兩臺tomcat,訪問 test.tomcat.com


可以看到,這裡出了點問題,重定向指向了  server.xml 中 host 為localhost 的目錄,而不是  test.tomcat.com

這是因為nginx轉發時未攜帶 host 資訊

開啟nginx.conf ,

       upstream tomcat {
      server 127.0.0.1:8080  weight=1;
      server 127.0.0.1:8081  weight=1;
    } 
    
    server 
    {
        listen  80;
        server_name  test.tomcat.com;
 
        location / {
       #     root   C:\xampp\htdocs\com;
            index  index.php index.html index.htm;
            proxy_pass http://tomcat;
        #        include proxy.conf;
			proxy_set_header Host $host;
        }


	}

加入紅色的這一句,標明代理時攜帶主機頭

nginx -s reload

重新訪問 test.tomcat.com


done.