【问题标题】:How to serve an angular app based on the URL using nginx?如何使用 nginx 基于 URL 提供 Angular 应用程序?
【发布时间】:2018-12-19 10:52:32
【问题描述】:

我想知道如何在使用 nginx 时根据 url 提供 angular 应用程序。因此,假设有一个名为 xyz.com/something/ 的 url,每当 url 中有内容时,我希望 ngnix 路由到 Angular 应用程序。我们如何实现它,我在 SO like this 上看到了类似的问题,但无法让它发挥作用。

location /something/ {
    root /var/www/xyz.com/html/something/;
    try_files $uri $uri/ /index.html =404;
    }

假设应用程序通常会响应网址,例如, xyz.com/something/login

以下代码运行良好。

location / {
  alias /var/www/xyz.com/html/something/;
  try_files $uri $uri/ /index.html =404;
}

也曾尝试使用 base-href 作为described here,但未能使其正常工作。

也尝试了第一个答案。

Nginx 配置文件:

location /admin {
    root /var/www/xyz.com/html/;
    try_files $uri $uri/ /admin/index.html;
}

location / {
    alias /var/www/xyz.com/html/user/;
    try_files $uri $uri/ /index.html =404;
}

这里的 /admin 和 /user 指的是存在于同一域中的两个不同的 AngularJs 项目。

测试用例:

URL : www.xyz.com/admin/
RESPONSE : Blank page.. 
           accessing index.html but not redirecting properly

URL : www.xyz.com/admin/login
RESPONSE : Blank page..
  ERRORS : Cannot match any routes. URL Segment: 'login'

但是我已经正确路由了..

有什么建议吗??

【问题讨论】:

  • 它找到的是index.html,而不是你的资源文件吗?
  • 是的,就是这样。

标签: angularjs nginx routing


【解决方案1】:

你有太多的“东西”。通过将 URI 附加到 root 的值来构造文件的路径。有关详细信息,请参阅this document

在您的配置中,文件术语 $uri$uri/ 将不匹配 andy 文件。

如果您从root 值中删除something,则需要将其添加到index.html 文件元素中。

例如:

location /something/ {
    root /var/www/xyz.com/html;
    try_files $uri $uri/ /something/index.html;
}

就我个人而言,我不附加=404,但这并没有什么坏处,而且我知道许多Angular 教程似乎都认为这是必要的。有关详细信息,请参阅this document

【讨论】:

  • 嘿,也尝试了你的建议。已经更新了上面问题的结果。请看一下。
【解决方案2】:
location /angular/ {
    root   /opt/app-root/src;
    index  index.html index.htm;
    try_files $uri $uri/ /angular/index.html;
}
COPY dist/angular-app/. /opt/app-root/src/angular

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 2021-01-13
    • 1970-01-01
    • 2018-06-16
    • 2015-01-18
    相关资源
    最近更新 更多