【发布时间】:2016-10-10 19:16:06
【问题描述】:
鉴于 Angular2 是一个单页站点,我们需要使用 Nginx 将所有 url 请求重定向到 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;
}
}
此配置在全局范围内运行良好。导航有效,我可以通过在浏览器中输入 url 直接访问我的页面。但是有两个问题:
- 当我在浏览器中输入一个 url 然后按回车键运行(或者如果我只是刷新页面),加载页面需要很长时间,接近 6 秒。但是,如果我从 Nginx 服务器块中删除重定向,则只需不到一秒钟。 但应用程序的导航(使用链接)按预期工作。
- 我的页面 (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);
我已经在 app.module.ts 文件的 @NgModule import 部分导入了 routing。
【问题讨论】:
标签: html nginx angular navigation