动静分离就是通过中间nginx中间件将静态请求和动态请求分开。分离资源后,减少不必要的请求消耗,减少请求延时,减轻服务器压力。

现在项目基本都是前后端分离,前端的项目结构,assets目录一般都是存放静态资源的

/src
|-assets 
   |-iconfont
   |-img
   |-lib
   |-...
|...

演示实例

服务目录

/opt/app/code8
|-api
   |-rand.php
|-assets
   |-css
      |-index.css
   |-image
      |-test.jpeg
|-index.html

/etc/nginx/conf.d
|-balancing.conf

rand.php

<?php
	echo rand(1,100);

index.css

*{
    padding:0;
    margin:0;
}

img{
    width:500px;
    height:auto;
}

index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="/assets/css/index.css">
</head>
<body>

    <div class="app">
        <h1> 随机数 <span id="rand"></span>  </h1>
        <img src="/assets/image/test.jpeg"/>
    </div> 

</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$.post("/api/rand.php",{name:'张三'},function(data){
    if(data){
        $('#rand').text(data);
    }
})
</script>

balancing.conf

server {
    listen       80; 
    server_name  walidream.com www.walidream.com;

    #charset koi8-r;
    access_log  /var/log/nginx/proxy_test.log  main;

    add_header Access-Control-Allow-Origin *;  
    add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;

    root /opt/app/code8;

    location / { 
        index index.html;
    }   

    location ~ .\.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;    
    }   

    location /assets {
        expires 4h; 
        gzip on; 
        gzip_http_version 1.1;
        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;

    } 
}	

当访问主页时,assets下面的静态资源css,js,image,iconfont等等就会被nginx缓存起来,动态请求数据则不会,从而实现动静分离。

ssl

nginx教程

nginx环境搭建(1) nginx基础知识(2) nginx的安装 卸载(3) nginx的基本参数使用(4) nginx分析默认配置(5) nginx 虚拟主机配置(6) nginx 日志(7) nginx 模块(8) nginx 访问控制(9) nginx 静态资源web服务(10) nginx 缓存(11) nginx 跨域访问(12) nginx 防盗链(13) nginx 正向,反向代理配置(14) nginx 代理缓存配置(15) nginx websocket(16) nginx fastcgi(17) nginx 搭建wordPress博客(18) nginx Fastcgi缓存配置(19) nginx uwsgi反向代理(20) nginx 负载均衡(21) [深] nginx 动静分离(22) [深] nginx rewrite规则(23) [深] nginx 平滑升级 添加模块 调试(24) [深] nginx secure_link_module模块(25) [深] nginx geoip_module模块(26) [深] nginx https(27) [深] nginx与lua的开发(28) [架] nginx常见问题(29) [架] nginx性能优化(30) [架] nginx 安全(31) [架] nginx 反向代理gRpc(32)