Nginx Angular2 html5mode PathLocationStrategy

Ben*_*Ben 0 navigation html5 nginx angular

鉴于Angular2是一个单页网站,我们需要使用Nginx将所有网址请求重定向到index.html.这是我的Nginx服务器块:

server {
    listen 8901;
    server_name my_server_ip;
    root /projects/my_site/dist;

    location /.+\..+ { # files (assuming they always have a dot)
        # use eg alias to serve some files here
    }

    location / { # url routed by client, client gives 404 for bad urls
        try_files $uri /index.html;
    }
}
Run Code Online (Sandbox Code Playgroud)

此配置全局运行良好.导航工作,我可以通过在浏览器中输入URL直接访问我的页面.但是有两个问题:

  1. 当我在浏览器中输入一个URL然后按回车键运行(或者如果我只是刷新页面),加载页面需要很长时间,接近6个secondes.但是如果我从Nginx服务器块中删除重定向,则只需不到一秒钟.但是通过应用程序的导航(使用链接)按预期工作.
  2. 我的页面(href)上有一个指向根目录的链接(http://my_site.com/,它是"主页"链接).如果我点击它,它会重新加载所有页面.这不是Angular2中的正确行为,它应该只是改变到家的路线.此问题仅发生在我的服务器上.如果我在我的本地机器上运行,一切运行良好,这就是为什么我认为问题来自我的Ngninx配置.

使用Nginx和Angular2有什么好的配置?

编辑: 我已经从angular.io的QUICKSTART项目开始了我的项目.这是我的app.routing.ts文件:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { LoginComponent } from './login/index';
import { HomeComponent } from './home/index';
import { ProfileComponent, ProfileConsultComponent, ProfileHomeComponent, CoachsComponent, AthletesComponent } from './profile/index';
import { FeedPostComponent } from './feedpost/index';
import { AuthGuard } from './_guards/index';

const appRoutes: Routes = [
    { path: '', component: HomeComponent, canActivate: [AuthGuard] },
    { path: 'login', component: LoginComponent },
    { path: 'profile/:pk', component: ProfileConsultComponent },
    { path: 'home', component: ProfileHomeComponent, canActivate: [AuthGuard],
        children: [
            { path: '', redirectTo: 'coachs', pathMatch: 'full' },
            { path: 'coachs', component: CoachsComponent },
            { path: 'athletes', component: AthletesComponent },
        ]
    },
    { path: 'post/:pk', component: FeedPostComponent, canActivate: [AuthGuard] },

    // otherwise redirect to home
    { path: '**', redirectTo: '' }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
Run Code Online (Sandbox Code Playgroud)

我已经routing@NgModule importapp.module.ts文件的部分导入了.

Ben*_*Ben 9

我已成功正确设置nginx以使用Angular 2按预期工作.这是我的服务器块:

server {
    listen 80;
    server_name my_server_name;
    root /projects/angular2/myproject/dist;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}
Run Code Online (Sandbox Code Playgroud)