使用 Angular 2 和 Apache 的路由器无法在生产模式下工作

Routers not working in prod mode using Angular 2 and Apache

我在生产模式下部署 angular4 应用程序时遇到问题。我正在按照 https://angular.io/guide/deployment 上指示的步骤进行操作。 apache 设置的目录是我项目中的 dist 文件夹。以下是我的项目的亮点:

app.module.ts

const appRoutes: Routes = [
        {  path: 'politica-privacidade', component: PoliticaPrivacidadeComponent },
        {  path: '', component: PaginaInicialComponent }
    ];

    @NgModule({
        declarations: [
            AppComponent
        ],
        imports: [
            BrowserModule,
            PaginaInicialModule,
            PoliticaPrivacidadeModule,
            RouterModule.forRoot(appRoutes)
        ],
        providers: [],
        bootstrap: [
            AppComponent
        ]
    })
    export class AppModule { }

.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

Apache 配置文件

<VirtualHost 80.241.208.103:80>
    ServerName coreografando.com.br
    ServerAlias www.coreografando.com.br
    ServerAdmin braulio@braulioti.com.br
    DocumentRoot "/var/www/coreografando/dist"
    ScriptAlias /cgi-bin/ "/var/www/coreografando/cgi-bin/"


    <IfModule mod_suphp.c>
        suPHP_UserGroup apache apache
        suPHP_ConfigPath /var/www/coreografando/dist
    </IfModule>

    <Directory "/var/www/coreografando/dist">
    </Directory>
</VirtualHost>

对于部署,我正在使用命令行:

ng build --prod

它可能与您构建应用程序的方式无关,而与您的服务器如何处理传入路由有关。我认为 ng serve 只是接受所有请求并将它们传送到 index.html,angular 路由器可以在其中采用所请求的路径。您当前的 apache 服务器执行其他操作。在我看来,您的 .htaccess 文件无法正常工作,尽管我不是很熟悉它。

angular-seed 项目有一个关于 github wiki 如何将 angular 构建部署到 apache 服务器的简短教程。这是他们的 .htaccess 的样子:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

对于其他必要的内容,您应该查看他们的教程,它不会那么长。我个人认为你的构建过程应该没问题,问题出在 apache 方面。

编辑

还有一件重要的事情,apache 配置应该为提供 Angular2 应用程序的目录启用 AllowOverride all。教程是这样说的:

Also for the rewrite module to work, the apache configuration should have AllowOverride all enabled for the directory where the Angular2 app is served. In the default cause this be done as following:

Open the file /etc/apache2/sites-enabled/000-default.conf Then add the following piece of code inside the VirtualHost block (assuming the Angular2 app is served from /var/www/html)

<Directory "/var/www/html">
  AllowOverride All
</Directory>