鑑於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;'。 –