【发布时间】:2019-08-07 12:27:56
【问题描述】:
我建立了一个包含几个组件的 Angular 网站。当使用ng serve 并在 localhost 上浏览时,路由工作得很好。但是当部署在云上时,只有起始页面在工作。路由到任何其他组件都不起作用,我收到错误:
404 Not Foundnginx/1.16.0.
我尝试使用 pathMatch: 'full' 等方法并创建一个启用 pushstate 的静态文件。
我也在使用<base href="/">。
应用路由模块:
const routes: Routes = [
{ path: '', component: IndexComponent, pathMatch : 'full'},
{ path: 'login', component: StartComponent, pathMatch : 'full'},
{ path: 'register', component: RegisterComponent, pathMatch: 'full'},
{ path: 'forgot', component: ServiceComponent, pathMatch: 'full'},
{ path: 'impressum', component: ImpComponent, pathMatch: 'full'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
export const routingComponents = [IndexComponent, StartComponent]
nginx 配置:
worker_processes 1;
events {
worker_connections 1024;
}
http {
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html index.htm;
include /etc/nginx/mime.types;
gzip on;
gzip_min_length 1000;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
location / {
try_files $uri $uri/ /index.html;
}
}
}
我不明白为什么 localhost 和服务器端路由存在差异以及如何修复它。
【问题讨论】:
-
确保您为您的应用设置了正确的
<base href="/"> -
我已经这样做了
-
我在 apache 服务器上遇到了类似的问题,按照以下方式解决了。可能这有帮助:joeljoseph.net/…
-
您需要将服务器设置为将非资产请求重定向到您应用的
index.html。目前,它正在尝试在您请求的 URL 处加载文件,而不是允许 Angular 处理路由。 -
感谢您的回复。请您详细解释一下好吗?
标签: html css angular nginx angular-routing