2

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

Nathan Long
  • 1,515
  • 7
  • 22
  • 38

1 Answers1

5

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;
  #...
}
Nathan Long
  • 1,515
  • 7
  • 22
  • 38
  • 4
    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](http://meta.stackexchange.com/questions/17463/can-i-answer-my-own-questions-even-if-i-knew-the-answer-before-asking); [rewarded even](http://serverfault.com/help/badges/14/self-learner). – 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