且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更改从单个 nginx 服务器提供的多个 Angular 应用程序的***路由?

更新时间:2023-11-22 18:37:22

如果您使用 ng serve 以这种方式在生产环境中部署 Angular 应用程序,我建议您更改它.使用 ng serve 应该只在开发中使用,因为包的大小很大并且会减慢网页的初始加载速度.

If you are deploying your angular apps this way in production using ng serve, I recommend you change that. Using ng serve should only be used in dev because the bundle size is huge and slows down initial load of the webpage.

推荐的部署到生产的方式是使用

Recommended way to deploy to production is using

ng build --prod

这会构建您的应用程序并将所有需要的文件放在/dist 文件夹中,根据您的 Angular 版本和设置,它可能位于子目录下.您应该将/dist 文件夹的内容复制到您的 nginx 容器中,并将 nginx 配置为指向您设置的路由的 index.html 文件.

This builds your app and puts all needed files in the /dist folder, possibly under a subdirectory depending on your angular version and settings. You should copy the contents of the /dist folder to your nginx container and configure nginx to point to the index.html file for the routes you set up.

例如,如果您将 app1 复制到/usr/share/nginx/html/app1 并将 app2 复制到/usr/share/nginx/html/app2,则您的 nginx 配置可能是(假设 index.html 文件位于/app1 和/app2 文件夹的根目录):

For example, if you copy app1 to /usr/share/nginx/html/app1 and app2 to /usr/share/nginx/html/app2 your nginx config could be (given that the index.html files are in the root of /app1 and /app2 folders):

location /app1 {
  try_files $uri /app1/index.html
}
location /app2 {
  try_files $uri /app2/index.html
}

这只是一个粗略的例子,理论上应该可行,但您很可能需要对其进行一些调整才能使其在您的设置中正常工作.

This is just a rough example, should work in theory but you most likely need to tweak it a little for it to work correctly in your setup.

如果你想指向两个开发容器的示例 nginx 配置:

Example nginx config if you want to point to the two dev containers:

http {
  upstream app1 {
    server app1:4200;
  }
  upstream app2 {
    server app2:4201;
  }
  server {
    ...
    location /app1/ {
      proxy_pass http://app1;
      ...
    }
    location /app2/ {
      proxy_pass http://app2;
      ...
    }
  }
}