Nginx+Apache动静分离详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/IT_10/article/details/89116208

什么是动静分离?

将客户端请求的动态页面和静态页面分开处理。

为什么要动静分离?

分离资源,减少不必要的请求损耗,减少请求延时。
当动态请求出问题时,不会引响到静态资源。

一般的请求分为如下步骤:请求->中间件->程序框架->程序逻辑->数据资源,然后再依次返回给请求客户端,而对于静态资源,其实只需要经过:请求->中间件->客户端,对于禁止缓存实时性较高的请求才会走上面的四个步骤。

实例

在apache的目录下放有random.php文件生成随机数

<?php
echo rand();
 
header('content-type:application:json;charset=utf8');
 header('Access-Control-Allow-Origin:*');
 header('Access-Control-Allow-Methods:GET');
 header('Access-Control-Allow-Headers:x-requested-with,content-type');
?>

在nginx的目录下放有测试文件test.html

  1 <!DOCTYPE html>
  2 <html>
  3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  4 <head>
  5 <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  6 <script type="text/javascript">
  7 $.ajax({
  8     type:"GET",
  9     url:"http://39.97.102.244:81/random.php"
 10 });
 11
 12 </script>
 13 </head>
 14 <body>
 15 <h1>动静分离测试</h1>
 16 <img src="http://39.97.102.244/dog.jpg" height="300" width="300"/>
 17 
 18 </body>
 19 </html>

在nginx的配置文件中添加代码如下:

location ~ \.php$ {
        root   /usr/share/nginx/html;
        proxy_pass http://php_api;
 }
location ~ \.(jgp|png)$ {
         root   /usr/share/nginx/html;
         expires 1h;
         gzip on;
}

//server外面
upstream php_api{
	server 你的apacheip;
}

这样,.php文件交给apache处理,静态文件交给nginx处理
打开apache、nginx,请求test.html
在这里插入图片描述
接下来,关闭apache,再次请求test.html
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/IT_10/article/details/89116208