1

I'm building a web app with Angular 1.x(not using ionic, building a website). I would like to remove the '#' from the URLs. I did implement html5mode true and put a base tag in the head tag in index.html. It works fine until I refresh the pages. When it is in html5mode it thinks that the URL is a request to the server. I'm developing in the local environment with gruntjs using the grunt-contrib-connect plugin and hosting my website in GoDaddy hosting in Linux Hosting Server. I would like to configure the html5mode(removing the hash from the URLs) in both environments(development and production). Note: I'm using ui.router with states if it matters in this problem.

  • HTML5 mode requires URL rewriting. For information, see [AngularJS Developer Guide - Using $location (HTML5 Mode Server Side)](https://docs.angularjs.org/guide/$location#server-side). – georgeawg Apr 02 '18 at 16:34

1 Answers1

0

By default, AngularJS will route URLs with a hash(#).

For example:

http://example.com/
http://example.com/#/about
http://example.com/#/contact

To remove the hashtag from the URL, you need to do two things

  • Configuring $locationProvider
  • Setting our base for relative links

$location Service

In AngularJS, the $location service parses the URL in the address bar and makes changes to application and vice versa.

$locationProvider and html5Mode

We will use the $locationProvider module and set html5Mode to true.

We will do this when defining Angular application and configuring routes.

angular.module('stackoverflow', [])

.config(function($routeProvider, $locationProvider) {

    $routeProvider
        .when('/', {
            templateUrl : 'partials/home.html',
            controller : homeController
        })
        .when('/about', {
            templateUrl : 'partials/about.html',
            controller : aboutController
        })
        .when('/contact', {
            templateUrl : 'partials/contact.html',
            controller : partialController
        });

    // use the HTML5 History API
    $locationProvider.html5Mode(true);
});

Setting Relative Links

To link around application using relative links, we will need to set a <base> in the <head> of your document.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">

    <base href="/">
</head>

There are many other ways to configure this and the HTML5 mode set to true should automatically resolve relative links.

Anil Arya
  • 3,100
  • 7
  • 43
  • 69