首页 > 解决方案 > 在 Nginx 代理后面的页面刷新后,我的 Angular 6 路由返回 404

问题描述

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

在主机服务器中,我有一个 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;
    }
}

使用上述配置,每个使用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
];

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

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);
    }
}

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

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

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

标签: javascriptangulartypescriptnginx

解决方案


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

server {
    listen 80;
    server_name mydomain.com;
    try_files $uri $uri/ /index.html @proxy;    

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

推荐阅读