动静分离是指将动态内容和静态内容分别由不同的服务器处理,以提高网站性能和可扩展性。
核心思想: - 静态资源(HTML、CSS、JS、图片等)由Nginx直接处理 - 动态请求(JSP、Servlet等)转发给Tomcat处理
/webroot/
├── static/ # 静态资源目录
│ ├── css/
│ ├── js/
│ └── images/
└── dynamic/ # 动态应用目录(Tomcat部署)
http {
upstream tomcat_server {
server 127.0.0.1:8080 weight=1;
# 可以添加更多Tomcat实例实现负载均衡
}
server {
listen 80;
server_name yourdomain.com;
# 静态资源处理
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
root /webroot/static/images;
expires 30d;
access_log off;
}
location ~ .*\.(js|css)?$ {
root /webroot/static;
expires 7d;
access_log off;
}
# 动态请求转发
location / {
proxy_pass http://tomcat_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 特定路径直接访问静态资源
location /static/ {
alias /webroot/static/;
}
}
}
expires
指令设置缓存时间access_log off
)<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
maxThreads="200"
minSpareThreads="25"
enableLookups="false"
acceptCount="100"
disableUploadTimeout="true"
compression="on"
compressionMinSize="2048"
compressableMimeType="text/html,text/xml,text/plain,text/css,text/javascript,application/javascript"/>
<%
String staticPath = request.getScheme() + "://" + request.getServerName() + "/static/";
%>
<link href="${staticPath}css/style.css" rel="stylesheet">
<script src="${staticPath}js/main.js"></script>
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|ico)$ {
if ($http_referer ~* "^https?://([^/]+\.)?yourdomain\.com") {
rewrite ^/(.*)$ http://cdn.yourdomain.com/$1 permanent;
}
}
upstream static_servers {
server static1.yourdomain.com;
server static2.yourdomain.com;
}
upstream dynamic_servers {
server tomcat1.yourdomain.com:8080;
server tomcat2.yourdomain.com:8080;
}
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary off;
gzip_disable "MSIE [1-6]\.";
Nginx监控:
nginx -t
测试配置nginx -s reload
重载配置ngx_http_stub_status_module
监控连接数Tomcat监控:
系统监控工具:
通过以上配置和优化,Nginx+Tomcat的动静分离架构可以显著提升Web应用的性能和可扩展性,静态资源的响应时间通常可以减少50%以上,同时降低Tomcat服务器的负载压力。