Serve multiple Angular applications from the same server with Nginx

I serve several applications angularfrom the same unit serverin Nginx. Therefore, to allow the user to go directly to specific user routes angularthat I declared without having to go through the home page (and avoid page 404), I forward these routes from nginx to every angular application index.html, I added try_filesto each location:

server {
    listen 80;
    server_name website.com;

    # project1
    location / {
        alias /home/hakim/project1/dist/;
        try_files $uri /index.html;
    }

    # project2
    location /project2/ {
        alias /home/hakim/project2/dist/;
        try_files $uri /index.html;
    }

    # project3
    location /project3/ {
        alias /home/hakim/project3/dist/;
        try_files $uri /index.html;
    }
}

This solution avoids the 404 error when switching to the angular route, but the problem is that when switching to /project2/or /project3/it is redirected to /project1/. This is clearly not what is expected, as I want each location to go to the /project-i/index.htmlcorresponding project.

+4
3

, .

, , , try_files - http://nginx.org/r/try_files,

, uri, .

, /index.html (.. , - ), , ; - - , , / location, GET /index.html HTTP/1.1 ( , nginx).

, , location (, /projectX/index.html), , (, =404, , ).

  • , try_files $uri /projectX/index.html;,

  • , try_files $uri /index.html =404;.

:

location /projectX/ {
    alias /home/projectX/dist/;
    try_files $uri /projectX/index.html; # last param is internal redirect
}

:

location /projectX/ {
    alias /home/projectX/dist/;
    try_files $uri /index.html =404;
}

, /projectX/index.html , /index.html .

+1

2:

<base href="/project2">
0

Change the first location to:

# project1
location /project1/ {
    alias /home/hakim/project1/dist/;
    try_files $uri /index.html;
}

The current block matches all '/', and this is the first that matches the query.

0
source

Source: https://habr.com/ru/post/1691827/


All Articles