Search code examples
angularapache.htaccessmod-rewrite

Angular App on Apache Server without rewrite rules


I need to deliver an Angular application to an external team. When they try to load directly a page they get a 404 Not found error. The server is an Apache and I haven't access to this server.

I have asked them that they should configure the server according to documentation (rewrite rules): https://angular.io/guide/deployment#server-configuration but they refuse to do it. I have no other choice. I need to run the Angular application anyway or redo the application completely using directly html and js.

I need a mechanism that loads always index.html and redirects to the destination page.

This is the build command:

ng build --prod --base-href=./

I've also tried attaching the rewrite rules in a .htaccess in the same folder than my index.html but it doesn't work for them either, maybe because they haven't enabled 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>

Solution

  • The other choice when you not available to setup rewrite rules on the server (specially when you are hosting the app in a third part host), is to use a old resource in Angular. Add {useHash: true} parameter in forRoot method:

    @NgModule({
      imports: [ RouterModule.forRoot(routes, {useHash: true}) ],
      exports: [ RouterModule ]
    })
    

    Automatically, any url pointed to http://yoururl.com/products, for example, will be rewrite to http://yoururl.com/#/products. You will just need to review for your menu and links to point to #/products, instead of /products.