Reputation: 15844
I have troubles to setup nginx with react router. I have tried all suggested solutions I found but none of them seems to cover my use case.
This is a structure on my filesystem served by nginx
/path/to/my/app
|- v1.0/index.html
`- v2.0/index.html
I have deployed several versions on my app, each is a standalone react app.
Then there's one more thing to complete the puzzle. My react app does not run on domain root URL (like example.com/v1.0
) but rather on example.com/my-app/v1.0
.
So I configured nginx like this
server {
location ~ /my-app/([^/]+) { # capture version
set $version $1;
root /path/to/my/app/$version # directory where index.html is stored
try_files $uri $uri/ /index.html
}
}
Accessing example.com/my-app/v1.0
works fine but if the path contains a route in react (example.com/my-app/v1.0/users
), nginx returns 404
because it wants to serve a file /path/to/my/app/v1.0/users
which obviously is not present.
Also it's worth to mention the my app does only work when accessed like example.com/my-app/v1.0/
not like example.com/my-app/v1.0/index.html
. The latter does not have any route configured.
Upvotes: 1
Views: 820
Reputation: 49822
One option is to use alias
with a prefix location
, for example:
location /my-app/ {
alias /path/to/my/app/;
if (-e $request_filename) {
rewrite ^(/my-app/[^/]+) $1/index.html last;
}
}
The values of the location
and alias
directive should both end with /
or neither end with /
. Avoid try_files
and alias
due to this issue. See this caution on the use of if
.
Another option is your approach, but replacing the try_files
terms with the correct values. For example:
location ~ /my-app/(?<version>[^/]+)(?<suffix>/.*)?$ {
root /path/to/my/app/$version;
try_files $suffix $suffix/ /my-app/$version/index.html;
}
Upvotes: 1