鉴于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;
}
}
此配置全局运行良好。导航工作,我可以通过在浏览器中输入URL直接访问我的页面。但有两个问题:
使用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文件的routing
@NgModule
部分导入import
。
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
您不应该向nginx添加重定向,而是更改应用程序服务器的路由,以便为包含有效客户端路径的应用程序的页面提供服务。
这里很好地解释了一个明确的应用程序。 (从凌晨2点开始)
修改强>
https://www.youtube.com/watch?v=ANfplcxnl78&index=2&list=PLOa5YIicjJ-VA38pChXHhq8jY2U8iYynr
对于nginx,应该是
location ~ ^/([^/]+)/([^/?]+)$ {
/index.html;
}
try_files将检查路径中的speciefied文件,但不起作用 您还需要删除第一个规范