windows下测试 nginx+tomcat实现java web项目的动静分离

1. 安装nginx,访问静态资源

安装成功后,启动nginx,浏览器输入http://localhost/出现欢迎页面.

在nginx下依次建立目录 static\test1\js\common,并将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,tomcat,myeclipse或idea等 ,创建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 type="text/javascript">
    //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文件,弹出提示框。

本机截图:

         

点赞(93)

评论列表共有 0 条评论

立即
投稿
返回
顶部