Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

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;
  #...
}
share|improve this answer
2  
So, you searched and found a solution within a minute. That's incredible! –  Pothi Oct 11 '13 at 12:39
    
@Pothi Self answering is highly encouraged; rewarded even. –  jscott Oct 11 '13 at 13:08
1  
@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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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