概述:
Nginx 动静分离简单来说就是把动态跟静态请求分开,不能理解成只是单纯的把动态页面和 静态页面物理分离。严格意义上说应该是动态请求跟静态请求分开,可以理解成使用 Nginx 处理静态页面,Tomcat 处理动态页面。
动静分离从目前实现角度来讲大致分为两种, 一种是纯粹把静态文件独立成单独的域名,放在独立的服务器上,也是目前主流推崇的方案;
另外一种方法就是动态跟静态文件混合在一起发布,通过 nginx 来分开。 通过 location 指定不同的后缀名实现不同的请求转发。通过 expires 参数设置,可以使 浏览器缓存过期时间,减少与服务器之前的请求和流量。
具体 Expires 定义:是给一个资 源设定一个过期时间,也就是说无需去服务端验证,直接通过浏览器自身确认是否过期即可, 所以不会产生额外的流量。此种方法非常适合不经常变动的资源。(如果经常更新的文件, 不建议使用 Expires 来缓存),我这里设置 3d,表示在这 3 天之内访问这个 URL,发送 一个请求,比对服务器该文件最后更新时间没有变化,则不会从服务器抓取,返回状态码 304,如果有修改,则直接从服务器重新下载,返回状态码 200。
实验代码:
1. 在linux中准备静态资源
1.1 创建静态资源文件夹
[root@VM-0-7-centos static]# pwd
/usr/local/static
[root@VM-0-7-centos static]# mkdir www image
[root@VM-0-7-centos static]# ll
total 8
drwxr-xr-x 2 root root 4096 Nov 18 09:55 image
drwxr-xr-x 2 root root 4096 Nov 18 09:55 www
1.2 上传文件
www 中上传 index.html
image 中上传 01.png
[root@VM-0-7-centos static]# cd www
[root@VM-0-7-centos www]# pwd
/usr/local/static/www
[root@VM-0-7-centos www]# rz
[root@VM-0-7-centos www]# cd ../image
[root@VM-0-7-centos image]# pwd
/usr/local/static/image
[root@VM-0-7-centos image]# rz
[root@VM-0-7-centos image]# ll
total 416
-rw-r--r-- 1 root root 424359 Oct 13 10:03 01.png
[root@VM-0-7-centos image]# cd ../www
[root@VM-0-7-centos www]# ll
total 4
-rw-r--r-- 1 root root 50 Nov 18 09:57 index.html
[root@VM-0-7-centos www]#
2. 具体配置
2.1 配置nginx配置文件
主要配置 server 中 location
root 为访问根目录 设置为准备好的静态资源目录 /usr/local/static
autoindex on : 可列出目录
server {
listen 1080;
server_name 127.0.0.1;
location /www/ {
root /usr/local/static/;
index index.html index.htm;
}
location /image/ {
root /usr/local/static/;
autoindex on;
}
}
2.2 保存配置后重启nginx
这里我已经配置nginx为环境变量。
[root@VM-0-7-centos conf]# nginx -s reload
[root@VM-0-7-centos conf]#
3. 访问测试
3.1 访问www/index.html
3.2 访问 image/01.png
3.3 autoindex on 作用
来源:oschina
链接:https://my.oschina.net/u/1020373/blog/4722178