nginx 文件路径的定义

下面介绍一下文件路径的定义配置项。php

(1)以root方式设置资源路径html

语法:root path;nginx

默认:root html;web

配置块:http、server、location、if正则表达式

例如,定义资源文件相对于HTTP请求的根目录。
location /download/ {
 root /opt/web/html/;
}服务器

在上面的配置中,若是有一个请求的URI是/download/index/test.html,那么Web服务器将会返回服务器上/opt/web/html/download/index/test.html文件的内容。fetch

(2)以alias方式设置资源路径网站

语法:alias path;spa

配置块:location.net

alias也是用来设置文件资源路径的,它与root的不一样点主要在于如何解读紧跟location后面的uri参数,这将会导致alias与root以不一样的方式将用户请求映射到真正的磁盘文件上。例如,若是有一个请求的URI是/conf/nginx.conf,而用户实际想访问的文件在/usr/local/nginx/conf/nginx.conf,那么想要使用alias来进行设置的话,能够采用以下方式:
location /conf {
   alias /usr/local/nginx/conf/;   
}

若是用root设置,那么语句以下所示:
location /conf {
   root /usr/local/nginx/;       
}

使用alias时,在URI向实际文件路径的映射过程当中,已经把location后配置的/conf这部分字符串丢弃掉,所以,/conf/nginx.conf请求将根据alias path映射为path/nginx.conf。root则否则,它会根据完整的URI请求来映射,所以,/conf/nginx.conf请求会根据root path映射为path/conf/nginx.conf。这也是root能够放置到http、server、location或if块中,而alias只能放置到location块中的缘由。

alias后面还能够添加正则表达式,例如:
location ~ ^/test/(\w+)\.(\w+)$ {
    alias /usr/local/nginx/$2/$1.$2;
}

这样,请求在访问/test/nginx.conf时,Nginx会返回/usr/local/nginx/conf/nginx.conf文件中的内容。

(3)访问首页

语法:index file ...;

默认:index index.html;

配置块:http、server、location

有时,访问站点时的URI是/,这时通常是返回网站的首页,而这与root和alias都不一样。这里用ngx_http_index_module模块提供的index配置实现。index后能够跟多个文件参数,Nginx将会按照顺序来访问这些文件,例如:
location / {
    root   path;
    index /index.html /html/index.php /index.php;
}

接收到请求后,Nginx首先会尝试访问path/index.php文件,若是能够访问,就直接返回文件内容结束请求,不然再试图返回path/html/index.php文件的内容,依此类推。

(4)根据HTTP返回码重定向页面

语法:error_page code [ code... ] [ = | =answer-code ] uri | @named_location

配置块:http、server、location、if

当对于某个请求返回错误码时,若是匹配上了error_page中设置的code,则重定向到新的URI中。例如:
error_page   404          /404.html;
error_page   502 503 504  /50x.html;
error_page   403          http://example.com/forbidden.html;
error_page   404          = @fetch ;

注意,虽然重定向了URI,但返回的HTTP错误码仍是与原来的相同。用户能够经过“=”来更改返回的错误码,例如:
error_page 404 =200 /empty.gif;
error_page 404 =403 /forbidden.gif;

也能够不指定确切的返回错误码,而是由重定向后实际处理的真实结果来决定,这时,只要把“=”后面的错误码去掉便可,例如:
error_page 404 = /empty.gif;

若是不想修改URI,只是想让这样的请求重定向到另外一个location中进行处理,那么能够这样设置:
location / (
    error_page 404 @fallback ;
)
 
location @fallback (
    proxy_pass http://backend;
)

这样,返回404的请求会被反向代理到http://backend上游服务器中处理。

(5)是否容许递归使用error_page

语法:recursive_error_pages [on | off];

默认:recursive_error_pages off;

配置块:http、server、location

肯定是否容许递归地定义error_page。

(6)try_files

语法:try_files path1 [path2] uri;

配置块:server、location

try_files后要跟若干路径,如path1 path2...,并且最后必需要有uri参数,意义以下:尝试按照顺序访问每个path,若是能够有效地读取,就直接向用户返回这个path对应的文件结束请求,不然继续向下访问。若是全部的path都找不到有效的文件,就重定向到最后的参数uri上。所以,最后这个参数uri必须存在,并且它应该是能够有效重定向的。例如:
try_files /system/maintenance.html $uri $uri/index.html $uri.html @other ;
location @other {
  proxy_pass http://backend;
}

上面这段代码表示若是前面的路径,如/system/maintenance.html等,都找不到,就会反向代理到http://backend服务上。还能够用指定错误码的方式与error_page配合使用,例如:location / {  try_files $uri $uri/ /error.php?c=404 =404;}

相关文章
相关标签/搜索