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/?


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;
| improve this answer | |
  • 3
    So, you searched and found a solution within a minute. That's incredible! – Pothi Kalimuthu Oct 11 '13 at 12:39
  • 1
    @Pothi Self answering is highly encouraged; rewarded even. – jscott Oct 11 '13 at 13:08
  • 3
    @Pothi - it's encouraged to the point that you can actually check a box while asking your question to provide the answer at the same time, which is what I did. :) I could have put this info in my personal notes, but I'd rather put it on the internet where it can help others. – Nathan Long Oct 11 '13 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.