Nginx – Why is Nginx serving `index.html` instead of a 404

http-status-code-404nginx

I have a site where requesting a particular JSON file and finding it missing triggers a request for a fallback JSON file. However, rather than getting a 404 for the first file, I was getting the contents of index.html, which isn't valid JSON and created an error.

I traced the problem to this directive:

location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to index.html
                try_files $uri $uri/ /index.html;
            }

How can I get it to serve a 404 for mysite.com/some/nonexistent/file.json, but still get index.html for mysite.com/?

Best Answer

After some reading, I changed the try_files directive:

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

# New way: serve a 404 response
try_files $uri $uri/ =404;

Another option would be:

# Fall back to this error page
try_files $uri $uri/ error_pages/404.html

I still have this directive to handle serving index.html for mysite.com/:

server {
  # ...
  index index.html index.html;
  #...
}
Related Topic