AngularJS + Nginx so 404 returns 404 and direct child route access returns AngularJS index file

I’ve been trying to find a solution for this for a while now but no luck so far. So here I am asking the question on Stackoverflow, hoping to get some questions answered.

I have an AngularJS app and an Angular app. They both need to be served from one Docker using one Nginx config. This is what I have so far in terms of Nginx config

server {
    listen 0.0.0.0:80;
    root /usr/share/nginx/html;

    location ^~ /legacy/ {
        add_header Cache-Control no-cache;

        try_files $uri $uri/ /index.html =404;
    }

    location / {
        add_header Cache-Control no-cache;

        try_files $uri $uri/ /index.html =404;
    }
}

That /legacy route is where all the AngularJS stuff is. So normally when user visits my site they should be taken to Angular app. However if they explicitly go to /legacy URL, they will get AngularJS app. Sounds simple enough, however because of my lack of knowledge in Nginx, I have not been able to achieve this.

Right now, /legacy takes me to the correct index.html file but that file is trying to load an asset that doesnt exist (btw I can’t edit any of the legacy code so removing this asset is out of question), in that case instead of returning 404 Nginx returns index.html itself. Which makes sense because of try_files directive. So I tried removing try_files directive and simply relied on autoindex on which worked fine when user went to just /legacy url. It stopped working when user directly tried to access a child route of legacy such as /legacy/home.

So my question would be, what changes do I need to make on the Nginx config side so that a missing asset would just throw 404 and when user dicrectly tried to access any child route of legacy (i.e /legacy/home) it would return the index.html from legacy directory.

Source: StackOverflow