且构网

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

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

更新时间:2023-11-22 18:32:40

如果使用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文件夹中,并可能在子目录下,具体取决于您的角度版本和设置.您应该将/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;
      ...
    }
  }
}