Nginx的try_files指令详解

Nginx的try_files指令详解

顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示文件夹),如果所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。
注:只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部的 URL 的指向。最后一个参数是回退 URL 且必须存在,否则会出现内部 500 错误。命名的 location 也可以使用在最后一个参数中。

举例说明
示例一:

nginx.conf: |
server {
listen 80;
listen [::]:80;
server_name magedu.com www.magedu.com;
index index.php index.html index.htm;
root /var/www/html;
location ~ /.well-known/acme-challenge {
allow all;
root /var/www/html;
}
location / {
try_files $uri $uri/ /index.html =404;
}
}


解释配置:

1.root:设置静态根目录为 /var/www/html

2.index:设置目录的默认文件为 index.html 、index.htm、index.php

3.try_files:设置文件查找规则为 $uri $uri/ /index.html。即3个规则,先从 $uri 查找,再从 u r i / 目录中查找,最后查找 / i n d e x . h t m l 。

4.例子:根据上面的配置,当请求http://localhost:3004/api时,uri 为 /api。当前try_file 具体为:/api、/api/、/index.html,其中 / 表示根目录(根据 root 或 alias 来指定)。

5.仅当以上都不存在时,NGINX才会触发404错误

查找逻辑:

首先:检查 /var/www/html 目录中是否存在 api 文件,如果存在,则返回文件;如果不存在,则进行下一步。
其次:检查 /var/www/html目录中是否存在 api/ 目录,如果存在,则在检查 api/ 目录中是否存在 index.html 或者 index.htm 文件(由 index 指定);如果存在,则返回该文件。如果不存在,则进行下一步。
最后:检查 /var/www/html 目录中是否存在/index.html文件。如果存在,则返回文件;如果不存在,则返回 404。
示例二:

location /pngs/ {
root /data/user/;
index index.html index.htm;
try_files $uri $uri/ /pngs/file.png;
}

根据上面的配置,当请求 http://localhost:3003/pngs/rule.png 时, $uri 为 /pngs/rule.png,当前 try_file 查找顺序为,首先是:/data/user/pngs/rule.png,其次是:/data/user/pngs/rule.png/ 文件下的 index 所配置的文件,即: index.html、index.htm,最后是: /data/user/pngs/file.png

暂无评论

发送评论 编辑评论

|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇