nginx在windows下的使用四

一、动静分离  

nginx的动静分离简单来说就是把动态和静态的请求分开。有的请求是请求静态资源的,有的请求是请求动态资源的,把这两个请求分开。比如请求一个图片,就是一个静态的资源,这个图片可以放在一个静态资源服务器上,发送图片的请求经过nginx转发到这个静态资源服务器上给出响应。比如从数据库中查询一个用户信息,是动态资源请求。
 
1.准备静态资源:
创建两个目录:
data/www.*.html
data/images/*.jpg
 
2.nginx.conf配置:
server {
    listen		 9003;
    server_name	 localhost;

    location / {
        root data/www;
    }

    location /images/ {
        root data/;
    }
}
解释:
1)  location / { root data/www;} :浏览器输入www/a.html时,没有其他的路径来匹配时,默认会匹配到location / 这个路径。
2)  root:在root配置的目录后面跟上url组成对应的文件路径,比如访问localhost:9003/index.html,经过nginx转换成localhost:9003/data/www/index.html
访问localhost:9003/images/2.jpg,转换成:http://localhost:9003/data/images/2.jpg 由于url路径中含有/images/是和location /images/匹配的,匹配完之后把2.jpg追加到root的配置路径/data/images的后面。
 
3)  ps:location /images/ { root data/images;} 这么写是不对的,root data/images;多写了个images。应该是data/;就行了。为什么呢?因为url中的/images/2.jpg匹配到location /images/之后,将/images/2.jpg就拼接在root的配置data/images后面就成了data/images/images/2.jpg。所以root配置写成data/;就行了。
 
总结:通过url去匹配静态资源即可。将动态资源和动态资源的请求url做有规律的一些识别分开即可。比如静态资源:static。
 
3.测试    
浏览器分别访问:http://localhost:9003/index.html     http://localhost:9003/images/2.jpg  正确访问,测试OK
 
 
 
 
 
 
 
 
 
 
 
---
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章