为什么 Nginx 提供 `index.html` 而不是 404?

Nat*_*ong 2 nginx http-status-code-404

我有一个站点,请求特定的 JSON 文件并发现它丢失会触发对后备 JSON 文件的请求。但是,我没有为第一个文件获得 404,而是获得了 的内容index.html,这不是有效的 JSON 并产生了错误。

我将问题追溯到这个指令:

location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to index.html
                try_files $uri $uri/ /index.html;
            }
Run Code Online (Sandbox Code Playgroud)

我怎样才能让它为404for服务mysite.com/some/nonexistent/file.json,但仍然得到index.htmlfor mysite.com/

Nat*_*ong 5

经过一番阅读,我更改了try_files指令:

# Old way: fallback to index.html
try_files $uri $uri/ /index.html;

# New way: serve a 404 response
try_files $uri $uri/ =404;
Run Code Online (Sandbox Code Playgroud)

另一种选择是:

# Fall back to this error page
try_files $uri $uri/ error_pages/404.html
Run Code Online (Sandbox Code Playgroud)

我仍然有这个指令来处理服务index.htmlmysite.com/

server {
  # ...
  index index.html index.html;
  #...
}
Run Code Online (Sandbox Code Playgroud)

  • 因此,您在一分钟内搜索并找到了解决方案。这是令人难以置信的! (4认同)
  • @Pothi - 鼓励您实际上可以在提出问题的同时选中一个框以提供答案,这就是我所做的。:) 我本可以把这些信息放在我的个人笔记中,但我宁愿把它放在互联网上,它可以帮助别人。 (3认同)
  • @Pothi [强烈鼓励自我回答](http://meta.stackexchange.com/questions/17463/can-i-answer-my-own-questions-even-if-i-knew-the-answer-before-询问);[甚至奖励](http://serverfault.com/help/badges/14/self-learner)。 (2认同)