1.nginx动静分离概念动静分离,通过中间件将动态请求和静态请求进行分离,分离资源,减少不必要的请求消耗,减少请求延时。
好处:动静分离后,即使动态服务不可用,但静态资源不会受到影响
通过中间件可以将动态请求和静态请求进行分离
2.nginx动静分离应用案例
2.1.环境规划系统 服务 服务 地址
centos7.5 负载均衡 nginx proxy 192.168.81.210
centos7.5 静态资源 nginx static 192.168.81.220
centos7.5 动态资源 tomcat server 192.168.81.230
2.2.配置静态资源1.创建动静分离配置文件[root@localhost ~]# cd /etc/nginx/conf.d/[root@localhost conf.d]# vim ds.conf#动静分离server { listen 80; server_name ds.com; location / { root /web; index index.html; } location ~* .*\.(png|jpg|gif)$ { root /web/images; }}2.重载nginx[root@localhost conf.d]# nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is oknginx: configuration file /etc/nginx/nginx.conf test is successful[root@localhost conf.d]# systemctl reload nginx3.准备图片[root@localhost conf.d]# mkdir /web/images[root@localhost conf.d]# wget -o /web/images/nginx.png http://nginx.org/nginx.png
2.3.配置动态资源1.编译安装tomcat[root@localhost soft]# tar xf apache-tomcat-7.0.92.tar.gz -c /application/2.写入动态文件[root@localhost soft]# cd /application/[root@localhost application]# vim apache-tomcat-7.0.92/webapps/root/java_test.jsp<%@ page language="java" import="java.util.*" pageencoding="utf-8"%><html> <head> <title>jsp test page</title> </head> <body> <% random rand = new random(); out.println("<h2>random number:</h2>"); out.println(rand.nextint(99)+100); %> </body></html>3.启动服务[root@localhost application]# cd apache-tomcat-7.0.92/[root@localhost apache-tomcat-7.0.92]# ./bin/startup.sh
2.4.整合动静分离2.4.1.配置动静分离负载均衡[root@localhost conf.d]# vim lb_ds.conf#整合动静分离upstream static_photo { server 172.16.1.20:80;}upstream java { server 172.16.1.30:8080;}server { listen 80; server_name ds.com; access_log /nginx_log/lb_ds_access.log main; location / { root /web/ds; index index.html; } location ~* .*\.(jpg|png|gif)$ { proxy_pass http://static_photo; proxy_set_header host $http_host; proxy_set_header x-real-ip $remote_addr; proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; } location ~* .jsp$ { proxy_pass http://java; proxy_set_header host $http_host; proxy_set_header x-real-ip $remote_addr; proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; }}
2.4.2.编写整合动静分离代码[root@localhost conf.d]# vim /web/ds/index.html<html lang="en"><head> <meta charset="utf-8" /> <title>测试动静分离</title> <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script></head><script type="text/javascript">$(document).ready(function(){ $.ajax({ type: "get", url: "http://ds.com/java_test.jsp", success: function(data) { $("#get_data").html(data) }, error: function() { alert("fail!!,请刷新再试"); } });});</script> <body> <h2>测试动静分离</h2> <h2>上面为静态图片,下面为动态页面</h2> <img src="http://ds.com/nginx.png"> <div id="get_data"></div> </body></html>
2.5.效果看着是一个页面实则不同机器在做处理
以上就是nginx动静分离及配置的方法是什么的详细内容。