【问题标题】:Nginx config for Angular 4 CLI appAngular 4 CLI 应用程序的 Nginx 配置
【发布时间】:2018-02-05 15:34:37
【问题描述】:

我已经研究了几个小时的 stackoverflow-answers 和 github 问题,但是我还没有找到合适的解决方案。

我有一个使用 Angular-CLI 构建的 Angular 4 应用程序。 我想从http://XYZ:80/angularapp 的 nginx 服务器(在 Docker 容器内)提供此应用程序。

为了拥有这个应用程序范围的基本href,我使用ng build --base-href /angularapp 构建了应用程序,它将<base href="/angularapp"> 添加到index.html 文件夹中的index.html

对于部署,我已将 dist 的内容复制到 /usr/share/nginx/html,我的 nginx 配置如下所示:

server {
    listen       80;
    server_name  localhost;

    location /api {
        # adjust port of backend to desired port
        proxy_pass http://backend:8081;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }

    location / {
        root  /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html$is_args$args;
    }
}

这绝对没问题,我可以通过转到http://XYZ:80/angularapphttp://XYZ:80/ 来访问该应用程序(将重定向到/angularapp)。

现在我尝试从另一个域(例如http://my-intranet/app)链接这个应用程序,该域也应该显示http://XYZ:80/angularapp 的内容。 但是,这会导致问题,因为所有资产的请求路径都错误(例如http://my-intranet/main.f574d09ce6036fc0840e.bundle.js)。因此,我收到错误Uncaught SyntaxError: Unexpected token <

我尝试使用--deploy-url /angularapp--deploy-url .,这会破坏原始应用程序网址 (http://XYZ:80/angularapp)。

有人可以就如何正确配置这种情况下的 nginx 位置提供帮助吗?提前谢谢!

【问题讨论】:

  • 试试这个ng build --prod --base-href .,它适用于每个域
  • 我如何必须在 nginx 配置中设置位置才能让应用程序在 http://XYZ:80/angularapp 而不是 http://XYZ:80 上运行?
  • 当你说我试图将http://my-intranet/app 链接到这个应用程序时。您是如何建立此链接的?
  • 很遗憾,由于此 DNS 映射是由外部提供商完成的,因此我对该过程没有任何了解。
  • 你查到这件事的底部了吗?如果是的话,介意分享吗?我也面临同样的问题

标签: angular nginx webserver angular-cli nginx-location


【解决方案1】:

当您在 angular-cli 中使用 nginx 的 try_files 指令和 --base-href 时。它会产生问题。

当 nginx 遍历您的 index.html 并查看 style.xxx.bundle.css、inline.xxx.bunble.js 和各种其他捆绑包的链接时。

由于--base-href 将/angularapp/styles.xxx.bundle.css 和/angularapp/inline.xxx.bunble.js 附加到链接,nginx 尝试定位块并执行try_files 指令以将URI 重定向到index.html。

这就是为什么你会看到

Uncaught SyntaxError: Unexpected token

为避免这种情况,您应该使用--deploy-url 并使文件夹路径与--base-href--deploy-url 同名,例如/usr/share/nginx/html/angularapp/ 并将dist 文件夹复制到那里。

然后应用程序将工作,否则删除 try_files 或不使用 --base-href

【讨论】:

    猜你喜欢
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2017-11-17
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    相关资源
    最近更新 更多