怎么實現nginx+tomcat的反向代理與動靜分離

1. 安裝nginx,訪問靜態資源

安裝成功后,啟動nginx,瀏覽器輸入http://localhost/出現歡迎頁面.

在nginx下依次建立目錄 Statictest1JScommon,并將jquery.xx.js 放進去。

ps: static 代表靜態文件主目錄,test1 代表tomcat下的項目名稱,本機使用jquery-1.12.1.min.js

修改配置文件nginx.conf,添加如下配置:

?#正則匹配以static開頭的請求,比如/test1/static/js…

?location ^~/test1/static/ {
??? alias?? static/test1/;??? #alias會把location后面配置的路徑丟棄掉; 使用alias時,目錄名后面一定要加/
?}

?重啟nginx,瀏覽器輸入http://localhost/test1/static/js/common/jquery-1.12.1.min.js 能夠訪問成功。

2.?構建Java web項目

?安裝jdk,tomcatmyeclipseidea等 ,創建web項目 test1。

?將test1歡迎頁設置成index.jsp,部署在tomcat下,端口號8080

?瀏覽器輸入http://localhost:8080/test1/能夠訪問成功。

3.?引入nginx下的靜態資源

?在index.jsp下引入nginx的jquery文件:

src=”http://localhost/test1/static/js/common/jquery-1.12.1.min.js”

同時編寫jquery測試腳本如下:

??<script>     //jquery語法,能夠成功alert說明jquery引入成功     $(function() {     alert("測試動靜分離成功!");     })    </script>

? 在nginx下配置test1項目的反向代理,修改nginx.conf,添加如下配置:

???#test1項目請求–> 反向代理到8080,其中^~/test1/static/請求除外
???location /test1/ {
???????proxy_pass http://localhost:8080;???
???}

4.?測試反向代理和動靜分離

重啟nginx,重啟tomcat!

瀏覽器輸入http://localhost/test1/,請求會被nginx轉發到8080端口的tomcat下面test1。

如果一切ok,瀏覽器會返回index.jsp的輸出,并且加載nginx下的jquery文件,彈出提示框。

本機截圖:

?????????怎么實現nginx+tomcat的反向代理與動靜分離

? 版權聲明
THE END
喜歡就支持一下吧
點贊9 分享