我需要向外部团队交付 Angular 应用程序。当他们尝试直接加载页面时,他们会收到 404 未找到错误。该服务器是 Apache,我无法访问该服务器。
我已要求他们根据文档(重写规则)配置服务器:https://angular.io/guide/deployment#server-configuration但他们拒绝这样做。我别无选择。无论如何,我需要运行 Angular 应用程序,或者直接使用 html 和 js 完全重做应用程序。
我需要一种始终加载index.html并重定向到目标页面的机制。
这是构建命令:
ng build --prod --base-href=./
我还尝试将重写规则附加到与我的index.html相同的文件夹中的.htaccess中,但这对它们也不起作用,可能是因为它们没有启用mod_rewrite:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
最佳答案
当您无法在服务器上设置重写规则时(特别是当您在第三方主机中托管应用程序时),另一种选择是使用 Angular 中的旧资源。在forRoot
方法中添加{useHash: true}
参数:
@NgModule({
imports: [ RouterModule.forRoot(routes, {useHash: true}) ],
exports: [ RouterModule ]
})
任何网址自动指向 http://yoururl.com/products例如,将被重写为 http://yoururl.com/#/products 。您只需检查菜单和链接以指向 #/products,而不是 /products。
关于Apache 服务器上的 Angular 应用程序无需重写规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59161304/