本篇主要介绍nginx 动静分离相关配置解析

动静分离是让动态网站里的动态网页根据一定规则把不变的资源和经常变的资源区分开来,动静资源做好了拆分以后,我们就可以根据静态资源的特点将其做缓存操作,这就是网站静态化处理的核心思路.
配置2台 虚拟机 并且都安装好nginx 服务,配置信息如下 , 并且在 hosts文件中做好域名配置
| ip | 模拟域名 | 类型 |
|---|---|---|
| 172.16.225.111 | www.testfront.com | 静态资源服务器 |
| 172.16.225.110 | www.testbackend.com | 动态资源服务器 |
主机电脑 /etc/hosts 文件配置如下
172.16.225.111 www.testfront.com
172.16.225.110 www.testbackend.com
第一步就简单的把 front 的请求 proxy_pass 到 backend 服务上去
注意需要在 front 的虚拟机中配置 /etc/hosts/ 172.16.225.110 www.testbackend.com 否则启动抛 host not found in upstream "www.testbackend.com"
worker_processes 1;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;server {listen 80;server_name www.testfront.com;location / {#这里使用域名所以需要在front本机上配置 etc/hostsproxy_pass http://www.testbackend.com; }#error_page 404 /404.html;# redirect server error pages to the static page /50x.html#error_page 500 502 503 504 /50x.html;location = /50x.html {root html;}}
}
backend 不需要配置, 只是在 html/index.html 修改内容 添加一个图片,并且标注了是backend 的 ip
...
Thank you for using nginx 172.16.225.110.
...
非动静分离是指 把静态资源直接放到 后端服务器上
根据上面的配置 当请求访问到 /my.gif 的时候 需要在backend 的 默认html/下要有这个my.gif文件

此时打开 www.testfront.com 和 www.testbackend.com 都会得到如下的界面

是指把静态资源 提取出来, 如上把 my.gif 提取到 front机器中,让所有访问静态资源的直接去front中访问
先把 backend机器中的 html/my.gif 静态资源删除了

以下配置 均在 front 机器上 即 172.16.225.111 上
配置 正则根据文件后缀去匹配 (不区分大小写)注意 正则匹配中 会把 /* 后面所有的路径都拼接到 /www/static/后面
....location ~* .(gif|jpg|jpeg|png|bmp|swf|css|js)$ {root /www/static;}
....
上面的配置意思是 当访问到 .gif... 等资源的时候 直接去 /www/static 下面寻找 相当于它访问了 /www/static/my.gif ,所以我这里要把my.gif 放入 /www/static下, 此时就能访问到了 并且是要通过 www.testfront.com ,而 www.testbackend.com 是无法访问到的,因为静态资源已经被移动到 front 服务器上了

以下配置 均在 front 机器上 即 172.16.225.111 上
以下位置块中的修饰符 ^~ 会导致区分大小写的正则表达式匹配.
以下 /static/my.gif 会被匹配到
....location ^~ /static/ {root /www/static;}
....
注意 root 是会把 location 中 /static/ 添加到 /www/static/ 后面 即 如果访问 /static/my.gif 会被匹配到 /www/static/static/my.gif
还有一种是 alias
....location ^~ /static/ {alias /www/static;}
....
注意 alias 是会忽略 location 中 /static/ 不会添加到 /www/static/ 后面 即 如果访问 /static/my.gif 会被匹配到 /www/static/my.gif
本篇主要介绍了 Nginx 动静分离的配置 主要有两种方式可以
还有介绍了 root 和 alias的区别
/www/static/static/my.gif/www/static/my.gif最后总结一下 location 的匹配优先级
欢迎大家访问 个人博客 Johnny小屋
欢迎关注个人公众号
