If you write a single-page app where the routing is handled on its own, it works perfectly on your local host with the dev server.
For an instance, if there is a route in your app for login such as "/login", if you try this in the localhost it will work without any issues.
If you host this with an Nginx server as a static web app, using the direct route in the URL will end up with 404.
try_files $uri $uri/ /index.html?q=$uri&$args;
This makes the Nginx look for files in the file path, and if found then serve it. Or else, route the request to the index.html.
In our example, it will look for a file called login in the static directory, since we don't have such a file it will route the request to the index.html, then handle the routing after that is up to the single page app.
This allows the single-page app to load its actual static files such as images, CSS, and js. If there are no such files, it will route the request to the index.html.
location / { root /usr/share/nginx/html; try_files $uri $uri/ /index.html?q=$uri&$args;
index index.html index.htm; }
Edit the configuration as above and reload the Nginx configuration as below.
sudo service nginx reload
Once this is done, the single-page app's routing should work even if you type in the URL and hit enter.
This solution is based on the Front Controller Pattern configuration for Nginx.
Thank you! Such a quick solution. I thought I'd spend a while trying to figure out the fix.
ReplyDelete