在 Nginx 上服务两个 SPA 应用程序

Serve two SPA applications on Nginx

我尝试在本地通过 nginx 服务两个 angular 应用程序

我有以下文件夹结构:

/html/page1

/html/page2

每个文件夹中包含每个应用程序的文件。

里面 page1:

3rdpartylicenses.txt
favicon.ico
index.html
main.14de877820428b623cf2.js
polyfills.f4b78b65941f8063fd57.js
runtime.06daa30a2963fa413676.js
styles.22f686fc418e8e8e0c6e.css

里面 page2:

3rdpartylicenses.txt
favicon.ico
index.html
main.275a9dc67ff328ee34fa.js
polyfills.4ea17e55c619d6f4aaad.js
runtime.b57bf819d5bdce77f1c7.js
styles.f7757684f1abbaee3fb9.css

这是我的 nginx.confg

worker_processes  1;

error_log  logs/error.log;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;


        location /page1{
            alias   html/page1;
            $uri $uri/ $uri/index.html /page1/index.html html/page1/index.html index.html
        }

        location /page2{
            alias   html/page2;
            $uri $uri/ $uri/index.html /page2/index.html html/page2/index.html index.html
        }


        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

}

when I try to access to http://localhost/page2/ or http://localhost/page2/ I get a blank page

在控制台中我看到错误:

GET http://localhost/styles.f7757684f1abbaee3fb9.css net::ERR_ABORTED 404 (Not Found) GET http://localhost/runtime.b57bf819d5bdce77f1c7.js net::ERR_ABORTED 404 (Not Found) GET http://localhost/styles.f7757684f1abbaee3fb9.css net::ERR_ABORTED 404 (Not Found) GET http://localhost/runtime.b57bf819d5bdce77f1c7.js net::ERR_ABORTED 404 (Not Found)

但是如果我 运行 URL http://localhost/page1/runtime.b57bf819d5bdce77f1c7.js 我得到文件没有任何问题。

为了 try_files 我已经尝试了很多方法。我认为问题在于那一行。

/location 文件夹运行良好,如果我放置静态索引文件,它们可以正常运行。

有什么建议吗?

nginx.conf 文件中需要以下配置:

location / { 
      root html; 
      try_files /page1$uri /page2$uri =404; 
}

location /page1{
      alias   html/page1;
      try_files $uri $uri/ $uri/index.html /page1/index.html;
}

location /page1{
      alias   html/page2;
      try_files $uri $uri/ $uri/index.html /page2/index.html;
 }

除了这些配置之外,我们还必须在 nginx 的 html 目录中创建名为 page1 和 page1 的文件夹。

并且在进行应用程序构建时,应用 --base-href 参数及其将按以下方式包含的文件夹的名称:

ng build --prod --base-href / page1

ng build --prod --base-href / page2