How to use html5Mode with Ionic?

I added $locationProvider.html5Mode(true); in the config function, and made sure I don’t use # in the urls.
But, I get an error: GET http://localhost:8100/app/players 404 (Not Found)

What else do I need to do to use the html5Mode in Ionic?

From AngularJS $location docs:

Server side

Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)

So you need to add this to your main .htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    # HTML5
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*) /#/$1
</IfModule>

Also don’t forget to setup the base path of your app’s index.html (i.e: <base href="/" />)

More info: AngularJS

1 Like

I use ionic serve to serve my app. Does ionic serve support this URL rewrite?

I’m almost certain that ionic serve (python SimpleHTTPServer) doesn’t support URL rewrite. You could give it a try. If it doesn’t work, try Apache or build a custom server using node.js.

You will have to create your own web server because ‘ionic server’ creates a server that don’t support modRewrite.

Here what I did:

1- Web Server for Production ( Nodejs + Express)

server.js

2- Web Server for Development ( Nodejs + Gulp + BroswerSync + Connect History Api Fallback)

gulpfile.js

3- Gulp task for Mobile App build (with gulp-replace package)

When you put <base href="/"> inside the head tag in your index.html file, the application will work fine with Html5Mode enabled in a web browser, but in your mobile application you gotta use <base href="."> instead.

To automate this, I created a gulp task with gulp-replace node package to do the job for me:

gulp.task('build:device', ['sass', 'compressJs', 'jade-templates'],function () {
  return gulp.src(paths.jade[1])
  	.pipe(replace('base(href="/")', 'base(href=".")'))
    .pipe(jade())
    .pipe(gulp.dest('./www/'));
});

So before I run "ionic build android" i run "gulp build:device" .

4- Url paths Cautions

You will have to be careful with url paths.

  • href urls must start with “/”. Ex.: <a href="/app/list">link</a>
  • src urls must start without “/”. Ex.: <img src="img/banner.jpg">

@lucasalmeida

thanks a lot for your post, I follow your instructions but I have an error
whe I run Ionic run android

this is my index.html

image

So when I run android I receive this error
image

Can any one help me?