问题
I have a React application and an admin dashboard which is built in Angular:
/var/www/example.com/example/web <- React
/var/www/example.com/example/admin <- Angular
This is my Nginx config:
server {
server_name example.com;
index index.html index.htm;
# React
location / {
root /var/www/example.com/example/web/build;
try_files $uri $uri/ /index.html;
}
# Admin
location /admin {
root /var/www/example.com/example/admin/dist;
try_files $uri $uri/ /index.html;
}
}
When I navigate to example.com/admin
it redirects me to the react application instead of the angular one.
I know this may have been asked a lot before but I've been trying to fix this all day with no luck :(
回答1:
This behavior occures because the last argument of try_files directive must be an URI or the HTTP error code. In your case, by processing request http://example.com/admin
resulting URI of the second try_files
directive will be /index.html
, which is in next turn will be processed with first location block and leads you to react application.
One solution is to put angular application into the admin
folder of the react application folder:
server {
server_name example.com;
index index.html index.htm;
# React folder
root /var/www/example.com/example/web/build;
location / {
try_files $uri $uri/ /index.html;
}
# Admin
location /admin {
# angular app must be in the /var/www/example.com/example/web/build/admin folder
try_files $uri $uri/ /admin/index.html;
}
}
This way resulting URI of the second try_files
directive will be /admin/index.html
, which leads you to angular application index file.
The second solution is to use an alias directive for the second location block:
server {
server_name example.com;
index index.html index.htm;
# React
location / {
root /var/www/example.com/example/web/build;
try_files $uri $uri/ /index.html;
}
# Admin
location /admin {
alias /var/www/example.com/example/admin/dist;
try_files $uri $uri/ /admin/index.html;
}
}
Note that resulting URI of the http://example.com/admin
request will be /admin/index.html
, which still will be processed by the second location block and served with the file /var/www/example.com/example/admin/dist/index.html
(if I use root
directive instead of alias
one, location prefix /admin
will be added to the path and the index file will be searched in the /var/www/example.com/example/admin/dist/admin
folder).
In both cases the absence of angular app index file in the folder in which nginx will look for it would be the reason of nginx HTTP 500 error because of infinite redirection to /admin/index.html
URI.
来源:https://stackoverflow.com/questions/59991520/nginx-2-locations-for-different-apps-react-and-angular