Nginx for react router spa
Background:
hosting react SPA using react-router using Nginx. There are some special config for the SPA. Otherwise, Nginx cannot find the right path and hence returning 404 to the user.
Issue:
When using the react-router to rout the react app. e.g. localhost:8000/login is routing to a login page of the react app. This is the way react-router routing the page. but in Nginx perspective, Nginx will treat as a request and searching for a sub-page. But the sub-page index.html isn't exist and Nginx will return default 404 back.
Solution:
As the react app is a SPA and the routing is managed by front-end react-router. Web server is only responsible for responding the index.html to the requester no matter what request is from the user.
The key config is the try_files $uri $uri/ /index.html =404;
It tells Nginx to response index.html for all request.
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html =404;
}
}