Nginx 配置实例-动静分离

概述:

Nginx 动静分离简单来讲就是把动态跟静态请求分开,不能理解成只是单纯的把动态页面和 静态页面物理分离。严格意义上说应该是动态请求跟静态请求分开,能够理解成使用 Nginx 处理静态页面,Tomcat 处理动态页面。html

动静分离从目前实现角度来说大体分为两种, 一种是纯粹把静态文件独立成单独的域名,放在独立的服务器上,也是目前主流推崇的方案;linux

另一种方法就是动态跟静态文件混合在一块儿发布,经过 nginx 来分开。 经过 location 指定不一样的后缀名实现不一样的请求转发。经过 expires 参数设置,可使 浏览器缓存过时时间,减小与服务器以前的请求和流量。nginx

具体 Expires 定义:是给一个资 源设定一个过时时间,也就是说无需去服务端验证,直接经过浏览器自身确认是否过时便可, 因此不会产生额外的流量。此种方法很是适合不常常变更的资源。(若是常常更新的文件, 不建议使用 Expires 来缓存),我这里设置 3d,表示在这 3 天以内访问这个 URL,发送 一个请求,比对服务器该文件最后更新时间没有变化,则不会从服务器抓取,返回状态码 304,若是有修改,则直接从服务器从新下载,返回状态码 200。centos

实验代码:

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.pngspa

[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. 具体配置3d

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 做用

相关文章
相关标签/搜索