nginx 如何在 try_files 中处理 =404 回退 [英] How nginx process =404 fallback in try_files

查看:624
本文介绍了nginx 如何在 try_files 中处理 =404 回退的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个示例 Web 服务器,在 www 目录中只有一个 index.html 文件.我可以使用以下配置设置 nginx:

I have a example web server with only one index.html file in a www directory. I can setup a nginx with following configuration:

location /subfolder {
     alias /data/www;
     try_files $uri $uri/ /index.html;
}

在浏览器中,我可以在我的本地域 test.local/subfolder 上看到正确的响应,而且 test.local/subfolder/something 返回一个默认的 nginx 页面(它是正常,因为没有设置root)

In browser I can see correct response on my local domain test.local/subfolder, also test.local/subfolder/something returns a default nginx page (it is normal because root is not set)

如果我将配置更改为

location /subfolder {
     alias /data/www;
     try_files $uri $uri/ /index.html =404;
}

test.local/subfolder 的响应仍然是正确的,但是 test.local/subfolder/something 和所有带有/subfolder 前缀的 URI 返回一个正确的 index.html响应状态也是 200 不是 404.如果我从 try_files 中删除 /index 我得到相同的结果

response to test.local/subfolder is still correct, but test.local/subfolder/something and all URI with /subfolder prefix return a index.html of correct response also status is 200 not 404. If I remove /index from try_files I get the same result

我想知道 nginx 如何使用 =404 回退处理请求,但找不到任何信息,甚至在官方文档中也找不到.

I wonder how nginx process request with =404 fallback, but cant find any information, not even in a official docs.

UDAPTE:

我发现别名指令应该以 / 结尾,但仍然没有得到 =404 的功能和目的,因为状态仍然是 200ok

I found out that a alias directive should end with an / but still dont get a =404 functionality and purpose because a status is still 200ok

推荐答案

try_files 指令仅支持以下语法:

The try_files directive only supports these syntaxes:

try_files file ... uri;
try_files file ... =code;

不支持:

try_files file ... uri =code;

这里fileuri的区别在于,对于file参数,NGINX会检查它们的存在在继续下一个论点之前;对于 uri,它不会.

The difference between file and uri here, is that for file arguments, NGINX will check their existence before moving on to next argument; for uri, it won't.

如果最后一个参数具有 =code 的形式,那么它之前的所有参数都是 files(检查是否存在).

If the last argument has form of a =code, then all prior arguments to it are files (checked for existence).

由此,您可以得出结论,请求 URI /foo/bar 和此配置:

From this, you can get a conclusion that with request URI /foo/bar and this config:

root /var/www;
location /foo/ {
  try_files $uri $uri/ =404;
}

...如果任何file存在,都不会触发404错误:

... Will not trigger 404 error if any of the files exist:

  • /var/www/foo/bar
  • /var/www/foo/bar/ 目录(如果您启用了 autoindex)
  • /var/www/foo/bar/index.html(或 index.php 等)(由于 index)
  • /var/www/foo/bar
  • /var/www/foo/bar/ directory (if you have autoindex enabled)
  • /var/www/foo/bar/index.html (or index.php, etc.) (due to value of index)

只有以上都不存在时,NGINX才会触发404错误.

Only when none of the above exist, NGINX will trigger 404 error.

这篇关于nginx 如何在 try_files 中处理 =404 回退的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆