skip to Main Content

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


  1. By default it looks like this:

    try_files $uri $uri/ =404;
    

    You don’t need that index.html in try_files, since you have it as index option value.

    Login or Signup to reply.
  2. 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:

    try_files $uri index.html; 
    

    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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search