Nginx + Tomcat 实现动静分离

来源:互联网 发布:c语言file的使用方法 编辑:程序博客网 时间:2024/05/21 14:53

因为基于不同的协议传输消息,一般的网络架构都是前端是Apache 或者 Nginx处理静态请求,Tomcat处理动态请求,做到动静分离,提高了网站和系统性能。

以下记录本地用nginx+tomcat实现的动静分离的主要步骤。

1. tomcat web应用jsp文件

路径:D:\nginx-1.8.0\Tomcat\tomcat-node1\webapps\examples\index.jsp

[html] view plaincopy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ page import="java.text.SimpleDateFormat"%>  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>  
  6.     <title>Tomcat集群测试</title>  
  7.   </head>  
  8.   <body>  
  9.     <%  
  10.         out.println("["+request.getLocalAddr()+":" +request.getLocalPort()+"]" + "<br/>session id:" + session.getId());   
  11.     %>  
  12.     <h1>images:</h1>  
  13.     <img src="jsp/images/code.gif" />  
  14.   </body>  
  15. </html>  

2. nginx主配置文件

[html] view plaincopy
  1. upstream local_tomcat {  
  2.        server localhost:18080;  
  3.        server localhost:18081;  
  4.     }   
  5.       
  6.     server {  
  7.         listen       80;  
  8.         server_name  localhost;  
  9.   
  10.         location / {  
  11.             root   html;  
  12.             index  index.html index.htm;  
  13.         }  
  14.           
  15.         # 所有静态请求都由nginx处理,存放目录为html  
  16.         location ~ \.(gif|jpg|jpeg|png|bmp|swf)$ {  
  17.             root    html;  
  18.         }  
  19.           
  20.         # 所有动态请求都转发给tomcat处理  
  21.         location ~ \.(jsp|do)$ {  
  22.             proxy_pass  http://local_tomcat;  
  23.         }  
  24.           
  25.         error_page   500 502 503 504  /50x.html;  
  26.         location = /50x.html {  
  27.             root   html;  
  28.         }  
  29.     }  

3. 拷贝静态文件

将图片复制到nginx本地目录,这里我们为了方便并且为了目录的一致性,将其源码全部拷贝至nginx节点:

D:\nginx-1.8.0\Tomcat\tomcat-node1\webapps\examples   ==========>   D:\nginx-1.8.0\html\examples  


4. 测试截图

访问URL:http://localhost/examples/index.jsp

刷新后:



0 0