Home > Blockchain >  NGINX configures front-end routing,404 cannot be returned
NGINX configures front-end routing,404 cannot be returned

Time:04-19

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;
} 

CodePudding user response:

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.

CodePudding user response:

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)

  • Related