Nginx 文件路径的配置

文件路径

root
root path;

默认root html;

配置块:http、server、location、if

Example

location /download/{
    root /opt/web/html;
}

那么当请求 /download/index/test.html 将返回 /opt/web/html/download/index/test.html

alias
alias path;

配置块:location

Example

location /download{
    alias /opt/web/html/download;
}

同样请求 /download/index/test.html 返回 /opt/web/html/download/index/test.html,与 root 不同的是,使用 alias 时,在URI 向实际文件路径映射的过程中已经将 location 后配置的路径完全丢弃了。

alias 后还可以添加正则表达式

Example

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

访问首页

index file ...;

默认:index index.html

配置块:http、server、location

index 后可以跟随多个文件,nginx 会按顺序访问

Example

location /{
    index /index.html /index.php
}

error_page

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

根据返回码重定向页面

配置块:http、server、location、if

Example:

error_page 404          /404.html;
error_page 502 503 504  /50x.html;
error_page 403          http://example.com/forbidden.html;
error_page 404          = @fetch;

用户可以通过 = 来更改错误码:

error_page 404          = 200   /empty.git;

也可以不指定确切的返回错误码:

error_page 404          =   /empty.git;

如果不想修改 URI ,只是将请求重定向到另一个 location:

location /  {
    error_page 404 @fallback;
}
location  @fallback {
    error_page http://example.com/forbidden.html;
}
recursive_error_pages
recursive_error_pages [on|off]

是否允许递归使用 error_page

默认off

配置块:http、server、location

try_files

try_files path1 [path2] uri;

用于在Nginx服务器中指定文件查找顺序,通常用于处理静态文件服务。它的作用是在请求到达Nginx服务器后,尝试按照指定的顺序查找文件,以满足请求。

配置块:server、location

try_file 后要跟若干 path,且最后必须有 URI 。Nginx将按照指定的顺序逐一尝试这些文件路径和URI,直到找到匹配项为止。

具体来说,try_files的作用是:

  1. 处理静态文件请求: 当客户端请求一个静态文件时(例如HTML、CSS、JavaScript、图片等),Nginx会按照指定的顺序尝试查找匹配的文件,并返回找到的第一个匹配项。

  2. 处理目录索引请求: 如果请求的是一个目录,而不是具体的文件,Nginx会尝试查找该目录下的默认文件,例如index.html,以返回给客户端。

  3. 处理错误页面: 如果找不到任何匹配的文件或目录,默认情况下,try_files还可以指定一个错误页面作为备选项,以处理404等错误。

Example

location / {
    try_files $uri $uri/ /index.html;
}

在这个示例中,Nginx首先尝试匹配请求的URI路径($uri),如果找到对应的文件,则直接返回该文件。如果找不到文件,则尝试匹配URI路径下的目录($uri/),如果存在对应的目录,则尝试查找该目录下的默认文件(通常是index.html)。如果仍然找不到匹配项,则最后返回index.html作为默认页面。

  • 23
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值