【问题标题】:Angular RouterModule - url navigation always "404 Not Found" after production buildAngular RouterModule - 生产构建后url导航总是“404 Not Found”
【发布时间】:2018-03-13 22:18:35
【问题描述】:

背景

我最近构建了我的第一个 Angular 4 应用程序,并使用 angular-cli 为 Apache 服务器生成了一个生产版本,在 Ubuntu 终端上使用以下命令:

ng build --base-href /my-new-app/ -prod

之所以这样是因为我的服务器包含由 apache 托管的其他应用程序,这些应用程序的地址如下:

http://my-server.com/my-other-app

问题

我的应用路由模块如下所示:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { MyComponent } from './my-comp/my-component.component';

const routes: Routes = [
  { path: '', redirectTo: '/my-comp', pathMatch: 'full' },
  { path: 'my-comp',  component: MyComponent },
  { path: '**', redirectTo: '/my-comp', pathMatch: 'full'}];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

如果我通过 http://my-server.com/my-new-app 访问该应用程序,它会正确重定向到 http://my-server.com/my-new-app/my-comp,如果我使用该应用程序导航它会正常,但 F5 刷新或使用 http://my-server.com/my-new-app/my-comp 在搜索栏上按 Enter 将我发送到“404 未找到”。

在开发时它工作正常,使用 ng serve --host 0.0.0.0 --open,但是它在 localhost:4200/my-comp 上打开,所以我'我猜这不太一样。

我在生产版本中做错了什么,除了第一条路线之外的每条路线都以 404 错误结束?

【问题讨论】:

  • 你的 index.html 上有<base href="/"> 吗?如果是这样,您的生产版本中的 href 是什么?
  • 是的,我在 @Gosha_Fighten,它是 正在开发中, 正在开发中

标签: angular typescript


【解决方案1】:

在根目录下创建一个.htaccess 文件并将其粘贴到里面

RewriteEngine On
    # If an existing asset or directory is requested go to it as it is
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
    RewriteRule ^ - [L]
    # If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 2016-11-19
    • 2014-11-18
    • 2021-12-15
    • 2018-01-04
    • 1970-01-01
    • 2012-08-16
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多