Tomcat动静分离
4259 字
21 分钟
Tomcat动静分离

Tomcat动静分离
[TOC]
会话保持

web01
(1)配置web01实现获取当前session—id[root@web01 ~]# cd /soft/tomcat/conf/[root@web01 conf]# vim server.xml <Host name="session.kpyun.com" appBase="/code/session/" unpackWARs="true" autoDeploy="false"> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="session" suffix=".log" pattern="%h %l %u %t "%r" %s %b" /> </Host>[root@web01 conf]# systemctl restart tomcat[root@web01 conf]# tail -2 /soft/tomcat/logs/catalina.outStarting ProtocolHandler ["http-nio-8080"]startup in [3203] milliseconds[root@web01 conf]# ll -d /code/session/drwxr-x--- 2 root root 6 Mar 25 08:49 /code/session/# 自动创建出来的[root@web01 conf]# mkdir /code/session/ROOT/'还需要手动创建ROOT目录'[root@web01 conf]# vim /code/session/ROOT/index.jsp<body> <% //HttpSession session = request.getSession(true); System.out.println(session.getCreationTime()); out.println("<br> web01 SESSION ID:" + session.getId() + "<br>"); out.println("Session created time is :" + session.getCreationTime() + "<br>"); %></body>[root@web01 conf]# systemctl restart tomcat'修改java的代码后,记得重启服务!'[root@web01 conf]# vim /etc/hosts10.0.0.7 session.kpyun.com[root@web01 conf]# curl -L session.kpyun.com:8080<body> <br> web01 SESSION ID:E1FEA6F67D150A9BBB6D66106F515A85<br>Session created time is :1774400130268<br>' Unix 时间戳(毫秒)'# 它不是我们日常习惯的“年-月-日 时:分:秒”格式# 人类不直观、但计算机处理时间常用这种方式,高效web02
(2)配置web02实现获取当前session—id[root@web02 ~]# cd /soft/tomcat/conf/[root@web02 conf]# vim server.xml... <Host name="session.kpyun.com" appBase="/code/session/" unpackWARs="true" autoDeploy="false"> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="session" suffix=".log" pattern="%h %l %u %t "%r" %s %b" /> </Host>[root@web02 conf]# systemctl restart tomcat[root@web02 conf]# mkdir /code/session/ROOT[root@web02 conf]# vim /code/session/ROOT/index.jsp<body> <% //HttpSession session = request.getSession(true); System.out.println(session.getCreationTime()); out.println("<br> WEB-02 SESSION ID:" + session.getId() + "<br>"); out.println("Session created time is :" + session.getCreationTime() + "<br>"); %></body>[root@web02 conf]# systemctl restart tomcat[root@web02 conf]# vim /etc/hosts10.0.0.8 session.kpyun.com[root@web02 conf]# curl -L session.kpyun.com:8080<body> <br> WEB-02 SESSION ID:710149EE7DD0DBA9B446C289C68DEAA0<br>Session created time is :1774401180301<br>lb负载
(3)配置负载均衡'session-id一直在跳'[root@lb01 ~]# cd /etc/nginx/conf.d/[root@lb01 conf.d]# vim se.confupstream se { server 172.16.1.7:8080; server 172.16.1.8:8080;}server { listen 80; server_name session.kpyun.com;
location / { proxy_pass http://se; proxy_set_header Host $http_host; proxy_http_version 1.1; }}[root@lb01 conf.d]# nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful[root@lb01 conf.d]# systemctl restart nginx[root@lb01 conf.d]# vim /etc/hosts10.0.0.5 session.kpyun.com[root@lb01 conf.d]# curl session.kpyun.com:8080curl: (7) Failed to connect to session.kpyun.com port 8080: Connection refused'我们应该访问的是默认80端口而并非是8080!'# 访问80代理着我们去访问后端web的8080[root@lb01 conf.d]# curl session.kpyun.com<br> web01 SESSION ID:5E3A86AFAEF8A8A49D5159F7EB7860C8<br># 🧩这次是web01--》60C8[root@lb01 conf.d]# curl session.kpyun.com<br> WEB-02 SESSION ID:1E000E9C5C03577A6E266AA14F8EBB85<br># ❗web02--》BB85[root@lb01 conf.d]# curl session.kpyun.com <br> web01 SESSION ID:E3767C74014D3E11C26DBE2B61733167<br># 🧩web01--》3167[root@lb01 conf.d]# curl session.kpyun.com<br> WEB-02 SESSION ID:BD16DAC1D5EAF2FC6F2C2901DA1723BD<br># ❗web02--》23BD💡'每次拉取页面session id都会变化'Redis缓存
(4)部署Redis✅ 10.0.0.51✅ yum -y install redis[root@db01 ~]# grep 172.16.1.51 /etc/redis.confbind 127.0.0.1 172.16.1.51requirepass 123456# 绑定172.xxx 后面是Redis的密码✅ systemctl start redis
1)上传redis插件[root@web01 ~]# cd /server/tmp/[root@web01 tmp]# rz# 上传软件包[root@web01 tmp]# ls | grep tomcat-cluster-redis-session-manager.ziptomcat-cluster-redis-session-manager.zip
2)解压[root@web01 tmp]# unzip tomcat-cluster-redis-session-manager.zip -d .# 解压到当前文件夹
3)拷贝'配置插件、修改默认的会话写入到redis'[root@web01 tmp]# cp tomcat-cluster-redis-session-manager/lib/* /soft/tomcat/lib/# 拷贝jars到tomcat的/lib目录中[root@web01 tmp]# cp tomcat-cluster-redis-session-manager/conf/redis-data-cache.properties /soft/tomcat/conf/# 拷贝conf下的redis.properties文件,到tomcat的conf文件
4)修改插件中的配置# 连接redis地址、密码[root@web01 conf]# vim redis-data-cache.properties[root@web01 conf]# egrep 'redis\.[hp]' redis-data-cache.propertiesredis.hosts=172.16.1.51:6379redis.password=123456
5)添加如下两行# 至tomcat/conf/context.xml# 添加在</Context> 上一行[root@web01 ~]# vim /soft/tomcat/conf/context.xml[root@web01 conf]# tail -3 context.xml <Valve className="tomcat.request.session.redis.SessionHandlerValve" /> <Manager className="tomcat.request.session.redis.SessionManager" /></Context># 最后这个Context是它自带的
6)同步给WEB02[root@web01 ~]# rsync -avz --delete /soft/tomcat/ 172.16.1.8:/soft/tomcat[root@web02 ~]# systemctl restart tomcat
7)测试验证[root@lb01 conf.d]# curl -L session.kpyun.com<br> web01 SESSION ID:3DBBD6F03336DC001EEF571B51E25EC6<br>[root@lb01 conf.d]# curl -L session.kpyun.com<br> WEB-02 SESSION ID:C386BBAAE2D9BCF6252C9E6CEEB9ECA8<br>'明明配置好Redis,可他还是在变!!'===================================================❌ curl 为什么每次 Cookie 都变?默认情况下,curl 不会自动保存和发送 Cookie每次 curl 请求都是“全新”的,没有携带之前的 JSESSIONID'你需要让 curl 保存并重用 Cookie'[root@lb01 conf.d]# curl -c cookies.txt session.kpyun.com<br> web01 SESSION ID:2F5EEE1B13FE44739705E2F4479E525C<br># -c:把响应中的 Cookie 保存到 cookies.txt[root@lb01 conf.d]# curl -b cookies.txt session.kpyun.com<br> WEB-02 SESSION ID:2F5EEE1B13FE44739705E2F4479E525C<br># -b:从文件中读取 Cookie 并在请求头中发送[root@lb01 conf.d]# curl -b cookies.txt session.kpyun.com<br> web01 SESSION ID:2F5EEE1B13FE44739705E2F4479E525C<br># 这次就都一样了!🧩可以再详细的复现一下这个过程!curl -vc cookies.txtcurl -vb cookies.txt===================================================✅'大家可以去参考Nginx05中的会话保持!'
8)浏览器测试访问解析:10.0.0.5 session.kpyun.com'session不会发生变化'

运行jar包
🧪java代码编译后: war包: 基于Tomcat运行 jar包: 部署运行环境JDK、命令行运行jar包、内嵌了轻量的tomcat==================================================='运行在web02上面!'# 关闭Nginx、Tomcat、PHP...'运行jar包只需要JDK就能把整个项目跑起来!'[root@web02 ~]# systemctl stop nginx[root@web02 ~]# systemctl stop tomcat[root@web02 ~]# systemctl stop php-fpm[root@web02 ~]# ss -lntupudp UNCONN 127.0.0.1:323 users:(("chronyd"udp UNCONN [::1]:323 users:(("chronyd"tcp LISTEN 0.0.0.0:22 users:(("sshd"tcp LISTEN [::]:22# 现在是比较干净的环境!'chronyd(校时)、远程登录(22)'
(1)部署运行环境JDK[root@web02 ~]# rpm -qa |grep jdkjdk1.8-1.8.0_181-fcs.x86_64[root@web02 ~]# java -versionjava version "1.8.0_181"Java(TM) SE Runtime Environment (build 1.8.0_181-b13)Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
(2)下载代码(jar包)# 通过页面管理nginx的项目https://gitee.com/cym1102/nginxWebUI/[root@web02 ~]# mkdir /home/nginxWebUI/# 创建存放jar包的目录[root@web02 ~]# wget -O /home/nginxWebUI/nginxWebUI.jar https://gitee.com/cym1102/nginxWebUI/releases/download/4.1.9/nginxWebUI-4.1.9.jar# 下载jar包、-O指定下载目录并重复名[root@web02 ~]# ll /home/nginxWebUI/total 43092-rw-r--r-- 1 root root 44122754 Mar 25 11:37 nginxWebUI.jar
(3)运行jar包[root@web02 ~]# yum -y install screenInstalled: screen-1:4.8.0-7.ky10.x86_64Complete![root@web02 ~]# screen -S java-web# 创建会话[root@web02 ~]# java -jar -Dfile.encoding=UTF-8 /home/nginxWebUI/nginxWebUI.jar --server.port=8080 --project.home=/home/nginxWebUI/===================================================-jar:接下来要运行的是一个可执行的 JAR 文件-Dfile.encoding=UTF-8:强制整个 Java 应用使用 UTF-8 编码处理字符串/home/nginxWebUI/nginxWebUI.jar:JAR文件的完整路径--server.port=8080:指定内嵌 Web 服务监听的端口为 8080--project.home=/home/nginxWebUI/:应用自定义的配置参数# 把 /home/nginxWebUI/ 目录作为项目的工作目录'> /dev/null'# 后面也可以定向到空!只有正确的定向到空'企业如果连接数据、需要添加数据库的启动参数'--spring.datasource.url=172.16.1.51--spring.datasource.username=root--spring.datasource.password=pass===================================================# ctrl+a+d脱离当前会话✅️正常退出,后面可以-r恢复[root@web02 ~]# screen -lsThere is a screen on: 3532.java-web (Detached)1 Socket in /run/screen/S-root.[root@web02 ~]# ss -lntup | grep 8080LISTEN *:8080 users:(("java",pid=3578,fd=35))# 这不就启动了[root@web02 ~]# ll /home/nginxWebUI/-rw-r--r-- 1 root root 1103 Mar 25 11:48 fastcgi.conf-rw-r--r-- 1 root root 1032 Mar 25 11:48 fastcgi_paramsdrwxr-xr-x 2 root root 28 Mar 25 11:48 log...-rw-r--r-- 1 root root 5448 Mar 25 11:48 mime.types-rw-r--r-- 1 root root 63 Mar 25 11:48 nginx.conf-rw-r--r-- 1 root root 44122754 Mar 25 11:37 nginxWebUI.jar# 刚开始这个目录下只有一个jar包!!'现在就更加的完整了!甚至有日志log'[root@web02 ~]# cd /home/nginxWebUI/log/[root@web02 log]# lltotal 4-rw-r--r-- 1 root root 2240 Mar 25 11:48 nginxWebUI.log[root@web02 log]# tail nginxWebUI.lognginxWebUI 4.1.9...Started..{HTTP/1.1,[http/1.1]}{http://localhost:8080}...Started (undertow 2.2.24/2.4.5) @288msEnd loading elapsed=2832ms pid=3578 v=2.4.5

[root@web02 log]# screen -lsThere is a screen on: 3532.java-web (Detached)1 Socket in /run/screen/S-root.[root@web02 log]# screen -r java-web# 再次进入到这个会话,Ctrl+d--》结束并退出会话![root@web02 log]# ss -lntup | grep 8080# 没有这个进程了!
(4)脚本启停# 最后将启动方式写入脚本nohup配合&把命令放在后台!![root@web02 scripts]# nohup ping -c3 www.baidu.com &>result.txt[root@web02 scripts]# cat result.txtnohup: ignoring input'nohup自己有一个输出!'PING www.a.shifen.com (180.101.49.44) 56(84) bytes of data.64 bytes from 180.101.49.44 (180.101.49.44): icmp_seq=1 ttl=128 time=24.2 ms...'但是没有放在后台'加上&就可以了![root@web02 scripts]# nohup ping -c3 www.baidu.com &>result.txt &[1] 4212===================================================1)脚本启动![root@web02 log]# cd /server/scripts/[root@web02 scripts]# vim st-jar.sh#!/bin/bashnohup java -jar -Dfile.encoding=UTF-8 /home/nginxWebUI/nginxWebUI.jar --server.port=8080 --project.home=/home/nginxWebUI/ &>/dev/null &[root@web02 scripts]# ll st-jar.sh-rw-r--r-- 1 root root 148 Mar 25 12:32 st-jar.sh[root@web02 scripts]# sh st-jar.sh[root@web02 scripts]# ss -lntup | grep 8080tcp LISTEN *:8080 (("java",pid=4236,fd=35))# 这不就启动了嘛!===================================================2)脚本暂停[root@web02 scripts]# ps axu|grep jar|grep -v greproot 4236 4.2 13.7 2411444 133844 pts/0 Sl 12:32 0:04 java -jar -Dfile.encoding=UTF-8 /home/nginxWebUI/nginxWebUI.jar --server.port=8080 --project.home=/home/nginxWebUI/[root@web02 scripts]# ps axu|grep jar|grep -v grep|awk '{print $2}'4236'过滤出进程号'[root@web02 scripts]# ps axu|grep jar|grep -v grep|awk '{print $2}'|xargs kill -9# 强制杀死[root@web02 scripts]# vim sp-jar.sh#!/bin/bashps axu|grep jar|grep -v grep|awk '{print $2}'|xargs kill -9[root@web02 scripts]# ll sp-jar.sh-rw-r--r-- 1 root root 72 Mar 25 12:37 sp-jar.sh===================================================测试验证![root@web02 scripts]# sh st-jar.sh[root@web02 scripts]# ss -lntup | grep 8080tcp LISTEN *:8080 (("java",pid=4597,fd=35))[root@web02 scripts]# curl localhost:8080 | head...<!DOCTYPE HTML><html><head> <title>nginxWebUI</title># 标题都出来了![root@web02 scripts]# sh sp-jar.shKilled[root@web02 scripts]# ss -lntup | grep 8080[root@web02 scripts]# curl localhost:8080curl: (7) Failed to connect to localhost port 8080: Connection refused动静分离

✅ 通俗版解释:
想象你开了一家餐厅:
- 🍜 “动态请求” = 客人点菜(需要厨师现做)→ 对应“程序逻辑+数据资源”
- 登录、下单、搜索 → 要走完整后端流程,慢一点但必要
- 🥤 “静态请求” = 客人要水、纸巾、菜单(直接拿就行)→ 对应“静态文件如图片、CSS、JS”
- 直接从服务器文件系统读取,快!
- ==视频确实是静态资源!==
以前呢?所有客人都挤在一个窗口排队,不管是要水还是要炒菜,都得等同一个服务员处理 → 慢!还容易堵!
现在用了“动静分离”,就像开了两个窗口:
👉 一个窗口专门发水/纸巾(静态资源) 👉 另一个窗口专门接单做菜(动态服务)
而且中间有个“负载均衡器”当调度员,谁该去哪边,它来分派!
🎯 总结一句话:
- 动静分离 = 把“不用动脑子的活”和“必须动脑子的活”分开干
- 各走各的路,互不拖累
- 就算一边罢工,另一边照样营业!
'不分离前!'⚠️后台的Tomcat用IP地址测试访问即可👉Nginx代理的时候,访问后台Tomcat不需要携带头步信息# proxy_set_header Host $http_host;# 后面Tomcat根本没有配置域名===================================================# web01测试![root@web01 ~]# cd /soft/tomcat/conf[root@web01 conf]# systemctl restart tomcat nginx
http://10.0.0.7:8080/
'Nginx转发'[root@web01 conf]# cd /etc/nginx/conf.d/[root@web01 conf.d]# vim tom.confserver{ listen 80; server_name tom.kpyun.com;
location / { proxy_pass http://127.0.0.1:8080; }}# win解析10.0.0.7 tom.kpyun.com
浏览器访问:http://tom.kpyun.com/===================================================如何找到小猫的图片❓️
1)用户访问Nginx的80端口2)将请求代理到本地的8080端口3)tomcat收到请求后读取自己的代码目录[root@web01 conf.d]# ls /soft/tomcat/webapps/ROOT/index.jsp/soft/tomcat/webapps/ROOT/index.jsp4)逐行读取里面的程序逻辑并找到小猫的图片位置[root@web01 conf.d]# ls /soft/tomcat/webapps/ROOT/tomcat.svg/soft/tomcat/webapps/ROOT/tomcat.svg5)tomcat拿到图片返回Nginx代理6)Nginx代理返回给用户单台实现
'nginx配置动静分离'
[root@web01 conf.d]#vim tom.confserver{ listen 80; server_name tom.kpyun.com;
location / { proxy_pass http://127.0.0.1:8080; }
location ~ \.(png|jpg|svg)$ { # 将静态图片匹配到/code/images root /code/images; }}[root@web01 conf.d]# nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful[root@web01 conf.d]# systemctl restart nginx[root@web01 conf.d]# mkdir /code/images[root@web01 conf.d]# ll /code/images/total 0# 里面什么都没有
'测试访问看不到猫'http://tom.kpyun.com/
当用户访问.svg图片时
~的优先级高于/所以跑到
/code/images里面拿图片
- 可是里面什么都没有!
'将tomcat图片拷贝到/code/images'[root@web01 conf.d]# ll /code/images/total 0[root@web01 conf.d]# find /soft/tomcat/webapps/ROOT/ -name "*.png" -o -name "*.svg".../soft/tomcat/webapps/ROOT/bg-button.png/soft/tomcat/webapps/ROOT/tomcat.svg[root@web01 conf.d]# find /soft/tomcat/webapps/ROOT/ -name "*.png" -o -name "*.svg" -exec cp {} /code/images/ \;[root@web01 conf.d]# ll /code/images/...-rw-r----- 1 root root 3103 Mar 25 16:35 bg-upper.png-rw-r----- 1 root root 67795 Mar 25 16:40 tomcat.svg
http://tom.kpyun.com/
[root@web01 conf.d]# ll /code/images/tomcat.svg-rw-r----- 1 root root 67795 Mar 25 16:40 /code/images/tomcat.svg# 属主是root,而我们Nginx是www用户,自然是没有任何权限的![root@web01 conf.d]# chown -R www:www /code/images/[root@web01 conf.d]# ll -d /code/imagesdrwxr-xr-x 2 www www 129 Mar 25 16:40 /code/images[root@web01 conf.d]# ll /code/images/tomcat.svg-rw-r----- 1 www www 67795 Mar 25 16:40 /code/images/tomcat.svg
'再次测试访问!'
集群实现

1.web01部署静态页面# 上传一张静态图片'这里我把nfs服务器关闭了--》图片在本地!'2.web02部署tomcat动态页面# 动态随机数--》刷新就给一个随机数3.配置location转发 静态的转发给web01//nginx 动态转发给web02//tomcat4.负载均衡配置index页面(包含静态和动态)5.测试模拟# 就算一边罢工,另一边照样营业!(1)web01创建静态页面[root@web01 conf.d]# vim s.confserver { listen 80; server_name s.kpyun.com;
location / { root /code/s; index index.html; }}[root@web01 conf.d]# nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful[root@web01 conf.d]# systemctl restart nginx[root@web01 conf.d]# mkdir /code/s[root@web01 conf.d]# echo Static From Web01 >/code/s/index.html[root@web01 conf.d]# ll /code/s/index.html-rw-r--r-- 1 root root 18 Mar 25 17:37 /code/s/index.html'静态资源最好的体现是用一张图片!'[root@web01 conf.d]# cd /code/s/[root@web01 s]# rz# 上传一张图片![root@web01 s]# ls -lh s.png-rw-r--r-- 1 root root 569K Mar 10 18:54 s.png
# windows解析测试10.0.0.7 s.kpyun.com

(2)web02部署动态随机数[root@web02 ~]# cd /soft/tomcat/conf/[root@web02 conf]# vim server.xml... <Host name="d.kpyun.com" appBase="/code/d/" unpackWARs="true" autoDeploy="false"> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="d.kpyun.com" suffix=".log" pattern="%h %l %u %t "%r" %s %b" /> </Host>[root@web02 conf]# mkdir -p /code/d/ROOT[root@web02 conf]# cd /code/d/ROOT/[root@web02 ROOT]# vim index.jsp<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><HTML> <HEAD> <TITLE>kpyun JSP Page</TITLE> <meta charset="utf-8"> <!-- 建议加上这个,防止中文乱码 --> </HEAD> <BODY> <% // 创建随机数对象 Random rand = new Random();
// 业务逻辑修改:生成 100 到 999 之间的随机数 // nextInt(900) 生成 0-899,加上 100 后即为 100-999 int randomNumber = rand.nextInt(900) + 100;
// 输出修复:修正了 </h1> 结束标签 out.println("<h1>kpyun随机数: " + randomNumber + "</h1>");
// 如果需要调试,可以在页面打印当前时间 // out.println("<p>生成时间: " + new Date() + "</p>"); %> </BODY></HTML>[root@web02 ROOT]# systemctl restart tomcat
[root@web02 ROOT]# vim /etc/hosts10.0.0.8 d.kpyun.com# Linux解析![root@web02 ROOT]# curl d.kpyun.com:8080 | grep kpyun | tail -1 <h1>kpyun随机数: 704</h1>[root@web02 ROOT]# curl d.kpyun.com:8080 | grep kpyun | tail -1 <h1>kpyun随机数: 541</h1>'他一直在变化!'#负载均衡集成后端的静态和动态资源修改nginx配置文件[root@lb01 conf.d]# cat tom.confserver { listen 80; server_name tom.ds.kpyun.com; root /code/tom_ds; index index.html;
location ~* \.(jpg|png|gif)$ { proxy_pass http://s.kpyun.com:80; }
location ~ \.jsp { proxy_pass http://d.kpyun.com:8080; }}1)没有携带请求头,因为后端web是两个不同的域名!# Nginx也是单独的一个域名!2)但是又不能直接访问IP,这里Nginx配置的是7层的代理![root@lb01 conf.d]# vim /etc/hosts172.16.1.7 s.kpyun.com172.16.1.8 d.kpyun.com'更改负载lb01本地的hsots表'[root@lb01 conf.d]# nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful[root@lb01 conf.d]# systemctl restart nginx
# win 解析10.0.0.5 tom.ds.kpyun.com

'在lb01中做一个页面把他俩融合进去!'[root@lb01 conf.d]# mkdir -p /code/tom_ds[root@lb01 conf.d]# cd /code/tom_ds[root@lb01 tom_ds]# vim index.html# 把下面这些代码复制上去!!<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <title>动静页面融合 - 调试版</title> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <style> body { font-family: Arial, sans-serif; padding: 20px; } .debug-box { border: 1px solid #ccc; padding: 10px; margin-top: 20px; background: #f9f9f9; } .status-ok { color: green; font-weight: bold; } .status-error { color: red; font-weight: bold; } </style></head><body> <h1>测试动静分离 (调试模式)</h1>
<!-- 图片区域 --> <div> <h3>1. 静态图片测试:</h3> <img src="/s.png" alt="Static Image" style="width: 200px; height: auto; border: 2px solid blue;"> <p id="img-status">正在检测图片...</p> </div>
<!-- 动态数据区域 --> <div class="debug-box"> <h3>2. 动态数据测试 (AJAX):</h3> <div id="get_data">等待加载...</div> <p id="ajax-status">正在请求 /index.jsp...</p> </div>
<script type="text/javascript"> $(document).ready(function(){ // --- 测试图片 --- var img = new Image(); img.src = "/s.png"; img.onload = function() { $("#img-status").html("<span class='status-ok'>✅ 图片加载成功!(尺寸: " + this.width + "x" + this.height + ")</span>"); }; img.onerror = function() { $("#img-status").html("<span class='status-error'>❌ 图片加载失败!请检查 Nginx 是否将 /s.png 正确代理到 s.kpyun.com</span>"); };
// --- 测试 AJAX --- $.ajax({ type: "GET", url: "/index.jsp", success: function(data){ $("#get_data").html(data); $("#ajax-status").html("<span class='status-ok'>✅ 动态数据加载成功!内容已渲染。</span>"); }, error: function(xhr, status, error) { var msg = "❌ 请求失败!\n状态: " + status + "\n错误: " + error; if(xhr.responseText) { msg += "\n返回内容: " + xhr.responseText.substring(0, 100) + "..."; } $("#ajax-status").html("<span class='status-error'>" + msg.replace(/\n/g, "<br>") + "</span>"); console.error("详细错误对象:", xhr); } }); }); </script></body></html>
- 测试: 停止web01nginx
- [root@web01 conf.d]# systemctl stop nginx

- 测试: 启动nginx、停止 web02 的tomcat
- [root@web01 conf.d]# systemctl start nginx
- [root@web02 ROOT]# systemctl stop tomcat

PC端和移动端分离
Nginx通过负载均衡'实现手机与PC调度至不同的后端节点应用案例'===================================================系统版本 主机角色 外网IP 内网IP 提供端口kylin 负载均衡 10.0.0.5 172.16.1.5 80kylin 提供Android页面 172.16.1.7 9090kylin 提供Iphone页面 172.16.1.7 9091kylin 提供pc页面 172.16.1.7 9092==================================================='web01基于多端口的多服务!'(1)web01配置静态资源[root@web01 conf.d]# cat s.confcharset utf-8;# 别忘记这个字符集,安卓打开会乱码的!!server { listen 9090; server_name diff.kpyun.com; location / { root /code/9090; index index.html; }}server { listen 9091; server_name diff.kpyun.com; location / { root /code/9091; index index.html; }}server { listen 9092; server_name diff.kpyun.com; location / { root /code/9092; index index.html; }}[root@web01 conf.d]#mkdir /code/909{0,1,2}[root@web01 conf.d]# ll -d /code/9*drwxr-xr-x 2 root root 6 Mar 25 20:26 /code/9090drwxr-xr-x 2 root root 6 Mar 25 20:26 /code/9091drwxr-xr-x 2 root root 6 Mar 25 20:26 /code/9092[root@web01 conf.d]# echo 提供Android页面 > /code/9090/index.html[root@web01 conf.d]# echo 提供Iphone页面 > /code/9091/index.html[root@web01 conf.d]# echo 提供pc页面 > /code/9092/index.html[root@web01 conf.d]# nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful[root@web01 conf.d]# systemctl restart nginx(2)负载均衡配置[root@lb01 conf.d]# cat m.confupstream android { server 172.16.1.7:9090;}
upstream iphone { server 172.16.1.7:9091;}
upstream pc { server 172.16.1.7:9092;}
server { listen 80; server_name diff.kpyun.com; charset 'utf-8';
location / {
# 如果客户端来源是Android则跳转到Android的资源; if ($http_user_agent ~* "Android") { proxy_pass http://android; }
# 如果客户端来源是Iphone则跳转到Iphone的资源; if ($http_user_agent ~* "Iphone") { proxy_pass http://iphone; }
# 如果客户端是IE浏览器则返回403错误; # 早就没有这个落伍的浏览器了 if ($http_user_agent ~* "MSIE") { return 403; } #默认跳转pc资源; proxy_pass http://pc; }}提问:❓️为什么这里没有携带头部信息!proxy_set_header Host $http_host;# 它是基于多端口的配置# 匹配的是同一个IP下,的特定端口# 所以即使不携带也能找到对应的配置信息.conf'但是还是推荐携带上!'[root@lb01 conf.d]# systemctl restart nginx
# win 解析10.0.0.5 diff.kpyun.com



[root@web01 conf.d]# tail -4 /var/log/nginx/access.log172.16.1.5 - - [25/Mar/2026:20:57:21 +0800] "GET / HTTP/1.0" 200 19 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1" "-"# iphone172.16.1.5 - - [25/Mar/2026:20:58:22 +0800] "GET / HTTP/1.0" 200 20 "-" "Mozilla/5.0 (Linux; Android 8.0.0; SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Mobile Safari/537.36" "-"# Android172.16.1.5 - - [25/Mar/2026:20:58:41 +0800] "GET / HTTP/1.0" 200 15 "-" "Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1" "-"# iPad172.16.1.5 - - [25/Mar/2026:20:59:29 +0800] "GET / HTTP/1.0" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36" "-"# win64注意: 除了UA可以做判断、其他所有的变量都可以用if判断 if ($remote_addr ~* 10.0.0.1 ) { proxy_pass http://www.baidu.com; }# 来源IP文章分享
如果这篇文章对你有帮助,欢迎分享给更多人!
相关文章智能推荐
1
前后端分离
Web服务前后端分离架构实战,涵盖Spring Boot后端、Nginx前端部署及四层七层负载均衡集群
2
Tomcat开篇
Web服务Tomcat应用服务器入门,涵盖JDK部署、server.xml层级、WAR包部署与Nginx反向代理集群
3
搭建企业内部yum仓库
Web服务企业内网YUM私有仓库搭建,使用createrepo+Nginx实现RPM包统一管理与离线快速分发
4
Keepalived 高可用
Web服务Keepalived高可用集群实战,讲解VRRP原理、主备部署、脑裂处理及Nginx健康检查自动切换
5
https证书部署
Web服务HTTPS证书部署与TLS加密实战,涵盖加密原理、自签名与真实证书配置及SSL参数优化
随机文章随机推荐



