Nginx——文件路径配置

文件路径的定义

以root方式设置资源路径

语法:root path;

默认:root html;

配置块:http、server、location、if

  location /data/ {
        root /web/html;
   }

如果请求的URI是/data/index/test.html,那么web服务器将返回/web/html/data/index/test.html文件的内容

alias设置资源路径别名

语法:alias  path;

配置块:location

    location /i/ {
        alias /data/w3/images/;
    }

如果一个请求的URI为 " /i/top.gif ",而实际想访问的是 /data/w3/images/top.gif,就可以使用上面的配置

如果用root的方式来设置,需要配置成如下语句:

    location conf {
        root /usr/local/nginx/;
    }

可以理解为alias就相当于一个软连接,匹配的时候location设置的路径将被丢弃。而root则是根据URI路径做映射。

alias后可以跟正则表达式:如

    location ~ ^/test/(w+).(w+)$ {
        alias usrlocal/nginx/$2/$1.$2;
    }    

首页设置

语法:index file...;

默认:index index.html;

配置块:http、server、location

index使用ngx_http_index_module模块实现。index后可以跟多个文件参数,这些文件将按顺序匹配。

    location  {
        root path;
        index index.html htmlindex.php /index.php;
    }    

这时,nginx首先尝试访问 path/index.php,如果可以访问就直接返回,否则,再试图访问 path/htmlindex.php

根据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_CODE。可以通过 "=" 更改返回的错误码。如

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 上游服务器中处理

try_files

语法:try_files path1 [path2] uri;
     try_files file ... =code;

配置块:server、location

try_files后要跟若干路径, 如path1 path2..., 而且最后必须要有uri参数,

意义如下:尝试按照顺序访问每一个path, 如果可以有效地读取, 就直接向用户返回这个path对应的文件结束请求, 否则继续向下访问。

如果所有的path都找不到有效的文件, 就重定向到最后的参数uri上。 因此, 最后这个参数uri必须存在, 而且它应该是可以有效重定向的。 例如:

location /images/ {
    try_files $uri $uri/ /images/default.gif;     #$uri表示文件,$uri/表示目录
} 
location
= /images/default.gif {
  expires 30s;
}

如果请求是 uri为/images/abc,

try_files 会先判断请求的是文件还是目录。如果是文件,那么与$uri匹配,找 /images下是否有这个abc文件,如果有就直接返回,如果没有就找第二个参数$uri/,找不到的时候用最后一个参数/images/default.gif处理

 

    try_files systemmaintenance.html $uri $uri/index.html $uri.html @other;
    location @other {
        proxy_pass http://backend;
    }

表示如果前面的路径都匹配不到,就反向代理至http://backend服务器上

try_files与rewrite的结合

  location  / {
                root  /var/www/build;
                index  index.html index.htm;
                try_files $uri $uri/ @rewrites;
        }
  
location @rewrites {
             rewrite ^(.+)$ /index.html last;
        }

也可以指定错误码和error_page配合使用,如

    location {
        try_files $uri $uri /error.phpc=404 =404;
    }
原文地址:https://www.cnblogs.com/zh-dream/p/12909834.html