Score:0

nginx returns 404 when serving React from subdirectory

mp flag

I've started with a React application served from nginx root. Then I followed this guide to serve the application from a sub-directory (/app). As suggested here, I changed my nginx config from this:

location / {
    root /usr/share/nginx/html;
    try_files $uri $uri/ /index.html =404;           
}

to this:

location /app {
    alias /usr/share/nginx/html;
    try_files $uri $uri/ /app/index.html =404;
}

This kinda works - I'm able to browse to https://localhost/app, and get all the static files as expected. My problem is with reloading URLs which are controlled by React Router (i.e. sending the nginx server a URL which includes parts after the /app). For example, before the change, both of the following worked:

  • https://localhost <-- works
  • https://localhost/auth/local <-- also works

The first simply returned the homepage. The second caused nginx to default to index.html, and React router took care to internally navigate to the correct page (/auth/local).

After the change, the first request works, but the 2nd fails with 404:

  • https://localhost/app <-- works
  • https://localhost/app/auth/local <-- fails with 404

By adding some debug headers, I see that after the change, in the 2nd case, nginx does not execute the block at all.

What am I doing wrong?

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.