Tutorial: Removing # from ionic PWA

I saw many people on forums, communities, and groups asking this question “How to remove the hash from the url in ionic 2?” So, I decided to take some time to do some research on it and I ended up with the following solution.

First, in your index.html file you shall add the following:

<base href="/">

Inside the head section.

Then, in your app.module.ts import the following dependencies:

import { PathLocationStrategy, LocationStrategy } from '@angular/common';

Then, inside your providers add the following snippet:

{provide: LocationStrategy, useClass: PathLocationStrategy}

With this the # on the url is now removed. However, with this, we are creating an error when trying to refresh the page. When you refresh the page, you get a 404 error or cannot GET…

To get ride of this error, you need extra rules on your server side. So, consider adding the following rules to your .htaccess file:

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

and for those using firebase hosting, consider reading this page https://www.firebase.com/docs/hosting/guide/url-redirects-rewrites.html#section-rewrites

2 Likes

Are you certain that doesn’t interfere with loading (for example) image assets?

I tested in on my app and all assets were loading correctly.

2 Likes

I am getting an error when I refresh the page, Cannot GET [PAGE_PATH].

How to fix this?

3 Likes