Nginx文件路径的定义

前一篇文章,记录了nginx中虚拟主机与请求分发,这一篇文件记录Nginx中文件路径的定义。
 
1.以root方式设置资源路径
语法:root path;
默认:root html;
配置块:http、server、location、if
如:
location /download/ {
    root webhtml;
}
在这个配置中,如果你访问/download/index/test.html,web服务器将会返回webhtml/download/index/test.html文件。
 
2)以alias方式设置资源路径
语法:alias path;
配置:location
alias配置与root配置一样,都是用来设置文件资源路径的,不同的地方在于如何解读location后面的url参数,这里用一个事例来记录。如果一个请求的url为/conf/nginx.conf,这个对应的文件在服务器的us r/local/nginx/conf/nginx.conf,那我们使用root和alias应该如何来配置呢?
location conf {
    alias usr/local/nginx/conf/;
    root usr/local/nginx/;
}
注:如果使用alias来指明路径的话,需要添加上conf,才能发挥正确的数据,root的话,会主动将匹配到的url前缀添加到路径中,所以不需要添加conf路径。
 
3)访问首页
语法:index file;
默认:index index.html;
配置块:http、server、location
一般情况下,直接访问域名的话,都会访问到网站的首页,在Nginx中首页是通过index参数来进行配置的,index后面可以跟多个文件参数,它会按顺序找到第一个文件。
 
4)根据返回码重定向页面
语法:error_page code[code...][=|=answer-code]url|@named_location
配置块:http、server、location、if
我们在访问一些网站时,可以看到一些错误页面,最常见的应该就是404了。在Nginx配置中,如果某一个请求返回错误吗时,匹配上来error_page配置中的code,请求将会重定向到新的url中。
如:
error_page 404 404.html;
error_page 502 503 50x.html;
error_page 403 http://example.com/forbidden.html;
error_page 404 = @fetch;
虽然重定向之后会返回指定的页面,但是返回的http的错误码还是与之前一致。可以通过如下方式来修改错误码:
error_page 404 = 200 empty.gif;
error_page 404 = 403 forbidden.gif;
也可以不指定返回码,就是返回重定向后的实际情况。
error_page 404 = /empty.gif;

如果不想修改url,而是要交给了一个loaction处理的话,可以如下:

location / {
    error_page 404 @fallbak;
}
location @fallbak {
    proxy_pass http://xxx.xxx.xxx.xxx/backend
}
 
5)是否可以递归使用error_page
语法:recursive_error_pages [on|off];
默认:recursive_error_pages off;
配置块:http、location、server
 
6)try_files
语法:try_files path1[path2]uri;
配置块:server、location
try_files后跟着若干个路径,最后必须有uri参数。其作用是:按顺序读取每一个文件,将成功读取到的第一个文件返回给用户,结束请求。如果没有找到一个可以有效读取的文件,就将请求重定向到uri上。
原文地址:https://www.cnblogs.com/52why/p/13287915.html