Linux – Nginx multiple location issue with react router

linuxnginx

I'm trying to setup an nginx for my React front-end. There is routes in it which handeld by React-router which using browser-history.

The locations basically:
domain.com/cm
domain.com/cm/dashboard
domain.com/cm/management
etc. following that

The current config looks like:

root         /srv/build;

location /cm {
    alias /srv/build/cm;
    index index.html
    try_files $uri $uri/ /index.html;
}

It is matching with the /cm and nothing else.

I tryed this with location ^~ /cm {} not worked, but it should be, because in the documentation it says matching everything which start with /cm

The solution which is working but ugly and not modulary is the following:

location /cm {}
location /cm/dashboard {}
location /cm/management {}

The same config inside the block is working. But in this case each time when we add a new route we should modify the nginx.

How can I solve it with only one location?

UPDATE

I discovered the main problem when I'm using the location /cm {alias /srv/build/cm} it is trying to do the following: /srv/build/cm/management when I want to reach the domain.com/cm/management. What I really need insted of is every route which start with /cm is should be alias to the /srv/build/cm not to /srv/build/cm/management or etc.

So if I type domain.com/cm/management I have to use the alias /srv/build/cm here too.

Best Answer

Have you try with only defining / instead of /cm :

location / {

for reference: https://stackoverflow.com/questions/35320674/how-can-i-have-same-rule-for-two-locations-in-nginx-config

UPDATE on multiple website condition:
If / represent another website then:

location ~ ^/(cm|dashboard|management)/ {
   root       /srv/build; 
}