【问题标题】:NGINX returns 404 even using proxy_pass即使使用 proxy_pass,NGINX 也会返回 404
【发布时间】:2017-01-20 22:50:28
【问题描述】:

我有一个 NGINX 服务器 (nginx1) 应该将所有请求代理到运行 Angular2 应用程序的 NGINX 服务器 (nginx2)。只有对 /api 的请求应该发送到 asp.net 核心服务器 (nginx3)。按照下面的nginx1配置:

 server { # should proxy all requests to nginx2 and /api to nginx3
    listen 80;
    server_name  mywebsite.com;
    location / {
        proxy_set_header Host $host;
        proxy_pass http://mywebsite.com:4999/;
    }
    # proxy para o backend
    location /api {
      proxy_pass http://mywebsite.com:5001;
      proxy_set_header Host $host;
    }
  }

按照下面的nginx2配置:

worker_processes  1;
events {
   worker_connections  1024;
}
http {
   include       mime.types;
   default_type  application/octet-stream;
   sendfile        on;
   keepalive_timeout  65;
   server {
       listen       4999;
       server_name  'mywebsite.com';
       location / {
           root   /usr/share/nginx/html; 
           try_files $uri$args $uri$args/ index.html;
       }
       #error_page  404              /error.html;
       # redirect server error pages to the static page /50x.html
       error_page   500 502 503 504  /50x.html;
       location = /50x.html {
           root   html;
       }
   }
}

如果我尝试打开 mywebsite.com,它会正确打开,但如果我输入完整的 angular2 路由(例如:http://mywebsite.com/orders),我会从 nginx1 收到错误 404。

我错过了什么?

【问题讨论】:

    标签: angular nginx proxy


    【解决方案1】:

    我认为您的问题不在于您的代理,而在于您的 NGINX2。在此服务器上,文件夹 /orders 不存在,并将向代理 NGINX1 返回 404 - 它只会将其返回给调用者。为了使其工作,您必须向 NGINX2 添加重写规则,将不是文件或文件夹的所有内容重写到您的主 angular2 index.html 文件。

    【讨论】:

    • 嗨 Mike,我刚刚在这篇文章中添加了 nginx2 配置。 nginx2 包含行 try_files $uri$args $uri$args/ index.html;
    • 好的,应该没问题。我看到的唯一奇怪的是你的 default_type application/octet-stream;
    • 我删除了'default_type application/octet-stream;'这一行。没有改变。不工作。 :-(
    • 如果您直接访问 NGINX2(在端口 4999 上) - 使用路径 /orders - 它会给出 404 吗?因为那会(也许)排除 proxy_pass
    • 另外,是否将 index.html 设置为您的索引文件? (在 http 块中:索引 index.html;)
    【解决方案2】:

    似乎与Angular2路由器有关。 我在我的 app.module.ts 中添加了以下几行(在 nginx2 下运行):

    import {HashLocationStrategy, LocationStrategy} from "@angular/common";
    
        providers: [
                {provide: LocationStrategy, useClass: HashLocationStrategy  },
                ...
        ]
    

    现在,只要我输入像http://mywebsite.com/#/orders 这样的完整网址或刷新任何页面,它都能完美运行。

    我仍然认为这不是最好的解决方案,因为现在每条路径都以'#'为前缀,但至少它有效。 :-)

    有关 angular2 HashLocationStrategy 的更多信息:https://angular.io/docs/ts/latest/guide/router.html

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 2019-10-13
      • 2011-07-16
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2020-03-26
      • 2020-02-24
      • 1970-01-01
      相关资源
      最近更新 更多