Nginx 和 Angular 路由(找不到 .js 文件)

Nginx and Angular Routing (can't find .js files)

我们 运行 遇到了正确显示使用 Nginx 服务的 Angular 路由页面的问题。 在我们的 Angular 项目中,我们的基本 href 是“/dashboard”。该项目有两条不同的路线指向“/dashboard/data-analysis”和“/dashboard/data-visual”。

这是我的基本 nginx.conf 文件:

server{
      listen 80;
      server_name localhost;

      location /dashboard/ {
          alias C:/Users/C123/Desktop/html/dashboard;
          index index.html;
          try_files $url $url/ /dashboard/index.html;
      }
}

当我继续“localhost/dashboard/”或“localhost/dashboard/data-analysis”时,任一页面都会从“C:/Users/C123/Desktop/html/dashboard/”加载 index.html,但是然后无法加载“polyfill.js”“runtime.js”“style.js”等,如 index.html.[=14= 的 <script> 标记中定义的]

此外,Nginx 尝试从“C:/Users/C123/nginx/nginx-1.16.1/html/”而不是我的别名 (C:/Users/C123/Desktop/html/dashboard).

加载这些文件

有没有一种方法可以在“dashboard/”位置块中定义它将从我的别名 index.html 中读取所有内容?我不想在外部定义根目录,也不想为“.js”文件定义辅助位置块。

更新(这个解决方案对我有用):

server{
      listen 80;
      server_name localhost;

      location /dashboard/ {
          root C:/Users/C123/Desktop/html/
          try_files $uri $uri/ /dashboard/index.html/
      }

您缺少 root 指令。

此外 try_files 应该尝试加载指定的文件,或目录中的 index.html

未测试,但应该有效:

server {
  listen 80;
  server_name localhost;

  location /dashboard/ {
      root C:/Users/C123/Desktop/html;
      try_files $uri $uri/index.html =404;
  }
}

编辑:

如果您尝试访问 dashboard 目录中的文件,但未在您的请求中指定单词 dashboard,您可以为此添加一个块以回退到。

server {
  listen 80;
  server_name localhost;

  # this will serve requests like http://localhost/runtime.js
  location / {
      root C:/Users/C123/Desktop/html/dashboard;
      try_files $uri $uri/index.html =404;
  }
  # this will serve requests like http://localhost/dashboard/
  location /dashboard/ {
      root C:/Users/C123/Desktop/html;
      try_files $uri $uri/index.html =404;
  }
}

请记住,当 NGINX 选择位置上下文时,它将来自提到的前缀位置的最长匹配

您可以在 angular.json 中设置 baseHref 和 deployUrl。 您可以在 projects -> $projectName -> architect -> build -> options 中设置它。

"deployUrl": "/dashboard/",
"baseHref": "/dashboard/",

有关这些参数的用途的更多上下文,请参阅