Ask a question, deploy React project with nginx, in order to configure the front-end routing of React Router, use $try_files for nginx to locate all routes into index.html, but there is a problem with this configuration,If you want to request other files, such as *.json, *.md, and if I request the json file in the directory, If the json file does not exist, the server will directly return the index.html file instead of returning 404. How to solve it?
location / {
alias /usr/local/var/www/;
index index.html;
try_files $uri index.html;
}
2
Answers
By default it looks like this:
You don’t need that
index.html
in try_files, since you have it asindex
option value.The configuration file you have set for NGINX is always going to fall back to index.html, as it will attempt to match try_files in order. What you need to add is
=404;
or better yet, change:to the implementation found in user973254s answer. Otherwise, NGINX is always going to fall back to
index.html
.Please see https://serverfault.com/questions/329592/how-does-try-files-work for a pretty detailed explanation. It directly addresses an instance where you append =404; to the try_files directive.
(Asked To Answer Via Queue)