在 Nginx 代理后面刷新页面后,我的 Angular 6 路由返回 404

Bro*_*mer 2 javascript nginx typescript angular

我的Angular应用程序在暴露在端口 83 上的docker内部运行,并且在另一个暴露在端口 8083 上的 docker 内部也有一个spring-boot Rest应用程序。

在主机服务器中,我有一个 Nginx 服务器,它使用以下配置重新路由每个请求:

server {
    listen 80;
    server_name mydomain.com;

    location / {
        proxy_pass http://127.0.0.1:83;
    }
}

server {
    listen 80;
    server_name rest.mydomain.com;

    location / {
        proxy_pass http://127.0.0.1:8083;
    }
}
Run Code Online (Sandbox Code Playgroud)

通过上述配置,每个使用mydomain.com 的请求都将转到我的 Angular 6 应用程序,每个使用rest.mydomain.com的请求都将转到我的 spring-boot Rest 应用程序。

在我的角度的索引页面中,我有一个搜索表单,它将触发路由模块打开搜索结果页面

我的app-routing.module.ts如下所示:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomePgComponent } from './home-pg/home-pg.component';
import { ResultsPgComponent } from './results-pg/results-pg.component';

const routes: Routes = [
  { path: "", component: HomePgComponent },
  { path: "search", component: ResultsPgComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(
    routes,
    { enableTracing: true }
  )],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule { }
export const RoutingComponents = [
  HomePgComponent, 
  ResultsPgComponent
];
Run Code Online (Sandbox Code Playgroud)

我的搜索表单上的触发器如下所示:

onSearchBtnClk(el) {
    if (el.value.length > 0) {
      console.log(">>> SEARCH ARGS = " + el.value);
      this.router.navigate(['/search'], { queryParams: { q: el.value }});
      this.newArgsEmitter.emit(el.value);
    }
}
Run Code Online (Sandbox Code Playgroud)

一切正常,当我单击搜索按钮时,我的角度将打开搜索结果页面并显示结果。

我的问题是,每当我单击浏览器上的REFRESH按钮时,它显示的不是搜索页面结果,而是404 page。为什么会出现这种情况呢?

任何意见,将不胜感激。谢谢

Pie*_*Duc 8

您需要添加一个try_files语句,但由于您使用的是 proxy_pass,这使得事情变得更加复杂。这是未经测试的,但你可以尝试这个:

\n
server {\n    listen 80;\n    server_name mydomain.com;\n    try_files $uri $uri/ /index.html @proxy;    \n\n    location @proxy {\n      proxy_pass http://127.0.0.1:83;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

\xe2\x80\x9c@\xe2\x80\x9d 前缀定义命名位置。这样的位置不用于常规请求处理,而是用于请求重定向。它们不能嵌套,也不能包含嵌套位置。

\n
\n

阅读更多

\n