Nginx动静分离基本概述
动静分离,通过中间将动静分离和静态请求进行分离;
通过中间件将动态请求和静态请求分离,可以建上不必要的请求消耗,同时能减少请求的延时。
通过中间件将动态请求和静态请求分离,逻辑图如下 :
动静分离只有好处:动静分离后,即使动态服务不可用,但静态资源不会受到影响。
Nginx动静分离场景实践
单台服务器实现动静分离
location / {
root /code/wordpress;
index.php;
}
location ~* \.(png|jpg|mp4)${
#指定图片路径
root /code/wordpress/images;
#压缩
gzip on;
.....
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
.....
}
多台服务器实现动静分离
环境准备
系统 | 作用 | 服务 | 地址 |
---|---|---|---|
Centos7.5 | 负载均衡 | nginx proxy | 10.0.0.5 |
Centos7.5 | 静态资源 | nginx static | 10.0.0.7 |
Centos7.5 | 动态资源 | tomcat server | 10.0.0.8 |
web01配置静态资源
[root@web01 ~]# cd /etc/nginx/conf.d/
[root@web01 conf.d]# cat ds_oldboy.conf
server {
listen 80;
server_name pic.drz.com;
root /code;
index index.html;
location ~* .*\.(jpg|png|gif)$ {
root /code/images;
}
}
#配置一个主页
[root@web01 conf.d]# echo "zls_test_web01" > /code/index.html
#创建图片目录
[root@web01 conf.d]# mkdir /code/images/
#上传一个静态文件
[root@web01 conf.d]# cd /code/images/
[root@web01 images]# rz bg1.jpg
[root@web01 conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 conf.d]# nginx -s reload
验证
打开浏览器访问