鉴于Angular2是一个页面的网站,我们需要将所有url请求重定向到index.html与Nginx。 这里是我的Nginx服务器块:Nginx Angular2 html5mode PathLocationStrategy
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;
}
}
这种配置在全球范围效果很好。导航工作正常,我可以通过在浏览器中输入url直接访问我的页面。但有两个问题:
- 当我输入在浏览器的URL,然后按Enter运行(或者,如果我只是刷新页面),它需要很长的时间来加载页面,接近6个secondes 。但是如果我从Nginx服务器块中删除重定向,它只需要不到一秒的时间。 但通过应用程序导航(使用链接)按预期工作。
- 我在我的页面(href)上有一个指向根的链接(http://my_site.com/,它是'home'链接)。如果我点击它,它将重新加载所有页面。在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);
而且我已经在我的app.module.ts文件@NgModule
import
部分进口routing
。
我认为最完整的设置会使用'try_files $ uri $ uri//index.html = 404;'。 –