nginx 后面的路由

Routing behing nginx

我有一个 angular2 应用程序。如果我使用本地 webpack dev server,一切正常。

当我在 nginx 后面的服务器上部署应用程序时 我可以使用应用程序链接进行导航。但是如果我在浏览器URL栏输入URL我得到404 Not Found错误.

这是站点的 Nginx 配置:

server {
    listen 80;
    server_name mydomain;

    location /api {
        proxy_pass http://mydomain:4000;
    }

    location /token-auth {
        proxy_pass http://mydomain:4000;
    }

    location / {
        root /www;
    }
}

这是我的申请详情:

<base href="/">

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes),

export const appRoutes:Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'rss', component: RssComponent, data: { section: 1 }, canActivate: [AuthGuard]  },
  { path: '', redirectTo: '/login', pathMatch: 'full' }
];

@Component({
  selector: 'my-app',
  template: `
<div id="application">  
    <app-navigation-tabs></app-navigation-tabs>   
</div>
<div>
    <router-outlet></router-outlet>
</div>
`,
  styleUrls: ['app.component.css']
})

<ul class="nav nav-tabs">
  <li role="presentation" [ngClass]="{active: currentSection === 3}"><a [routerLink]="['/rss']" (click)="toggleSection(3)">RSS</a></li>

我不确定是Nginx配置错误,还是我的应用程序错误。我该如何解决?

我是一个 apache 的人(不要怪我,这不是我的错,而是我的系统管理员的错)。但是对于每个使用 History API 的单页应用程序,您需要将请求重写为 index.html。我发现 this googling for nginx pushstate 似乎适用于 nginx。所以我想如果你改成这个它应该可以工作。

server {
    listen 80;
    server_name mydomain;

    location /api {
        proxy_pass http://mydomain:4000;
    }

    location /token-auth {
        proxy_pass http://mydomain:4000;
    }

    location ~ ^/.+/$ {
        root /www;
        rewrite .* /index.html last;
    }
}

编辑: 这个解决方案似乎不起作用,但我会深入挖掘并在发现问题时进行更新。否则删除。

我已经通过将 useHash 添加到我的路由器解决了我的问题:

RouterModule.forRoot(appRoutes, { useHash: true }),