首页 > 解决方案 > Move sites to subdirectories without changing base href

问题描述

I had two staging/test servers hosting each one an angular application on nginx, say app1 and app2. Everything was so simple:

http://<ip for app1 server>/   => app1
http://<ip for app2 server>/   => app2

Now I would like to host both application on a singleserver. Something like:

http://<ip for single server>/app1/   => app1
http://<ip for single server>/app2/   => app2

I would like to achieve that without changing the base href of my angular application (I know I could do that by changing it with the --baseHref=... option. But as I don't know how my application will be hosted when hitting the production phase, I would like to be baseHref agnostic...

So I wrote something maybe to naïve like:

location /app1/ {
    root /opt/myapps/;
}
location /app2/ {
    root /opt/myapps/;
}

And on the server, I put my sites into both /opt/myapps/app1 and /opt/myapps/app2 on the filesystem.

But when I try to open the app1 for example, nothing works as I only get the index.html (from http://\<ip for single server>/app1/). The assets don't get loaded because those are taken from the server root and not from the app1 subdirectory (for example http://\<ip for single server>/favicon.ico instead of http://\<ip for single server>/app1/favicon.ico)

Is that even possible? How can I achieve that?

标签: angularnginxnginx-location

解决方案


If you don't know the path at which the angular app will be hosted, you could put a relative href in appropriate index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title> Dashboard</title>
    <!-- relative href -->
    <base href="./" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
      <!-- Render angular app -->
    <app-root></app-root>
  </body>
</html>

推荐阅读