Nginx+Tomcat实现动静分离

原理:Nginx处理静态资源请求,Tomcat处理动态请求,做到动静分离,提高了网站和系统性能。

效果
a、访问http://localhost,加载test.gif图片,图片存放在静态资源(如放在D:\div\nginx-1.9.14\html\img),直接从nginx获取请求,不用请求tomcat服务器。访问http://localhost代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>列表</title>
</head>
<body>
    我是首页入口
   <!-- test.gif图片是从nginx请求的 -->
<img src="/img/test.gif"> </body> </html>

b、访问http://localhost/user/getPassword,动态请求tomcat服务器,从数据库获取密码显示到页面。


这里只需要修改Nginx的配置,让它通过Nginx处理静态请求,Tomcat处理动态请求。
1、nginx.conf配置文件

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  10;
    include extra/upstream01.conf;
}

 

2、extra/upstream01.conf文件,配置负载均衡、动态请求、静态文件请求等信息

# 转发的服务器,upstream为负载均衡做准备
upstream tomcat_server {
    server localhost:8080; #localhost:8080为tomcat server访问路径
}
 
server {
    listen 80;
    server_name localhost; #tomcat主机域名
  
    #默认将请求转发到tomcat_server配置的upstream进行处理
    location / {
        proxy_pass http://tomcat_server;
    }

    #所有js,css相关的静态资源文件的请求由Nginx处理
    location ~.*\.(js|css)$ {
        root html; #所有js,css文件指定路径
        expires 12h; #页面缓存,设置过期时间为12小时,若要清除页面缓存删除浏览器缓存即可
    }

    #所有图片等多媒体相关静态资源文件的请求由Nginx处理
    location ~.*\.(html|jpg|jpeg|png|bmp|gif|ico|mp3|mid|wma|mp4|swf|flv|rar|zip|txt|doc|ppt|xls|pdf)$ {
        root html; #所有图片文件指定路径
        expires 7d; #页面缓存,设置过期时间为7天,若要清除页面缓存删除浏览器缓存即可
    }

}

 

posted on 2017-03-19 00:13  Ruthless  阅读(1189)  评论(0编辑  收藏  举报