226

I'm learning AngularJS and there's one thing that really annoys me.

I use $routeProvider to declare routing rules for my application:

$routeProvider.when('/test', {
  controller: TestCtrl,
  templateUrl: 'views/test.html'
})
.otherwise({ redirectTo: '/test' });

but when I navigate to my app in browser I see app/#/test instead of app/test.

So my question is why AngularJS adds this hash # to urls? Is there any possibility to avoid it?

pikkvile
  • 2,521
  • 2
  • 14
  • 16
  • 2
    Here is [**the solution**](http://stackoverflow.com/questions/41226122/url-hash-bang-prefix-instead-of-simple-hash) if you are using Angular 1.6. – Mistalis Mar 29 '17 at 12:06

10 Answers10

267

In fact you need the # (hashtag) for non HTML5 browsers.

Otherwise they will just do an HTTP call to the server at the mentioned href. The # is an old browser shortcircuit which doesn't fire the request, which allows many js frameworks to build their own clientside rerouting on top of that.

You can use $locationProvider.html5Mode(true) to tell angular to use HTML5 strategy if available.

Here the list of browser that support HTML5 strategy: http://caniuse.com/#feat=history

Fedy2
  • 2,959
  • 2
  • 22
  • 41
plus-
  • 40,996
  • 14
  • 55
  • 71
  • 4
    OK, thank you. This is something what I suspected. But as for me this is pretty user-unfriendly! Let say I want some resource to be available via url, app/res. How can users of my site find out that they should type app/#/res instead? – pikkvile Jan 14 '13 at 15:53
  • Users should not have to type url manually, but navigate through the site UI if possible. – plus- Jan 14 '13 at 15:57
  • 5
    But if so, why do I need these paths to be visible in location bar? If users won't use them, I can just make single-page javascript application. – pikkvile Jan 14 '13 at 18:05
  • 6
    It's usefull when you want to keep track of the application state. The frameworks offer a history mechanism. Additionally, it allows direct access a state of your application via url sharing for instance – plus- Jan 14 '13 at 18:09
  • 6
    The hashtag is not required in modern browsers that support the HTML5 history API. See @skeep's answer and the links provided. In HTML5 mode, Angular will only use hashtags if the browser doesn't support it. Note also, you don't have to use $routeProvider if you don't want to... you can wire up your own routing using ng-clicks and ng-include (actually you have to do this if you need multiple levels of routing, since ng-view can only appear once per page). See also http://stackoverflow.com/questions/12793609/app-design-using-angular-js – Mark Rajcok Jan 15 '13 at 03:13
  • @MarkRajcok Thanks for the precisions. Correcting the answer accordingly – plus- Jan 15 '13 at 07:55
  • 2
    For the hashbang/pushstate/server-side rendering html case, the Twitter one is pretty nice to read http://engineering.twitter.com/2012/12/implementing-pushstate-for-twittercom_7.html It explains how they managed to do it so it's backward compatible with old browser and with search engines. I know it's not angularjs specific but you can reproduce the flow. – jackdbernier Apr 25 '13 at 23:56
  • Just want to add for anyone reading, non HTML5 browsers do NOT require the hash and can absolutely be routed properly by entering either with or without the hash. See my answer below. – bearfriend Oct 02 '13 at 21:03
  • @Doob it's worth noting that Twitter eventually moved away from using hashes `#` in their urls, for many reasons, including performance. You can read about it at [Improving performance on twitter.com](https://blog.twitter.com/2012/improving-performance-on-twittercom) and also the disadvantages (and there are big ones) to using `#` at [It's About The Hashbangs](http://danwebb.net/2011/5/28/it-is-about-the-hashbangs). –  Feb 19 '14 at 06:57
  • 1
    @solid7 post your comments about the answer in a _comment_, don't try to edit the answer and change its meaning. – uvesten Apr 08 '14 at 20:49
  • The Twitter link changed to https://blog.twitter.com/2012/implementing-pushstate-for-twittercom – Leo Caseiro Apr 21 '15 at 23:34
  • Also need to add in the head tag to avoid javascript errors in console. [explained on scotch.io](https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag) – ankit9j Jun 30 '17 at 20:02
47

If you enabled html5mode as others have said, and create an .htaccess file with the following contents (adjust for your needs):

RewriteEngine   On
RewriteBase     /
RewriteCond     %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_FILENAME} !-d
RewriteRule     ./index.html [L]

Users will be directed to the your app when they enter a proper route, and your app will read the route and bring them to the correct "page" within it.

EDIT: Just make sure not to have any file or directory names conflict with your routes.

Shivek Parmar
  • 2,528
  • 2
  • 30
  • 41
bearfriend
  • 8,336
  • 2
  • 19
  • 26
  • is there an nginx version of this? when i load `/about` the page fails unless I come to it through the app. – chovy Nov 26 '13 at 20:04
  • Never used them, but try this: http://stackoverflow.com/questions/5840497/convert-htaccess-to-nginx – bearfriend Nov 27 '13 at 14:34
  • 3
    @chovy - here goes nGinx version: server { server_name my-app; root /path/to/app; location / { try_files $uri $uri/ /index.html; } } – Moin Haidar Jul 16 '14 at 10:04
  • 4
    remember in head tag – Silvio Troia Dec 27 '14 at 16:31
  • Thanks! without this, deep linking is impossible. I am still not sure the prettiness or URIs is worth the trouble of maintaining this if you need deep linking, especially in some cloud/paas environments wher you might not have easy access to httpd config. – Pierre Henry Sep 06 '16 at 07:03
  • It didn't work for me unless I put `RewriteRule (.*) index.html [L]` as last line – Alessandro Dionisi Jan 14 '19 at 16:15
39

Lets write answer that looks simple and short

In Router at end add html5Mode(true);

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

    $routeProvider.when('/home', {
        templateUrl:'/html/home.html'
    });

    $locationProvider.html5Mode(true);
})

In html head add base tag

<html>
<head>
    <meta charset="utf-8">    
    <base href="/">
</head>

thanks To @plus- for detailing the above answer

vijay
  • 7,715
  • 8
  • 49
  • 69
  • I have not been able to get this to work. I have posted a new question with my specific details at: http://stackoverflow.com/questions/36041074/angularjs-routing-without-the-hash-cannot-get-it-work Please look at this and if you can help I would greatly appreciate it. – Larry Martell Mar 16 '16 at 16:10
30

try

$locationProvider.html5Mode(true)

More info at $locationProvider
Using $location

BByrne
  • 13
  • 5
skeep
  • 930
  • 6
  • 13
  • 6
    sorry i added .config(function($locationProvider){ $locationProvider.html5Mode(true) }) but i have result index.html#%2Fhome not index.html/home – zloctb Sep 11 '14 at 12:59
12

The following information is from:
https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag

It is very easy to get clean URLs and remove the hashtag from the URL in Angular.
By default, AngularJS will route URLs with a hashtag For Example:

There are 2 things that need to be done.

  • Configuring $locationProvider

  • Setting our base for relative links

  • $location Service

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

I would highly recommend reading through the official Angular $location docs to get a feel for the location service and what it provides.

https://docs.angularjs.org/api/ng/service/$location

$locationProvider and html5Mode

  • We will use the $locationProvider module and set html5Mode to true.
  • We will do this when defining your Angular application and configuring your routes.

    angular.module('noHash', [])
    
    .config(function($routeProvider, $locationProvider) {
    
       $routeProvider
           .when('/', {
               templateUrl : 'partials/home.html',
               controller : mainController
           })
           .when('/about', {
               templateUrl : 'partials/about.html',
               controller : mainController
           })
           .when('/contact', {
               templateUrl : 'partials/contact.html',
               controller : mainController
           });
    
       // use the HTML5 History API
       $locationProvider.html5Mode(true); });
    

What is the HTML5 History API? It is a standardized way to manipulate the browser history using a script. This lets Angular change the routing and URLs of our pages without refreshing the page. For more information on this, here is a good HTML5 History API Article:

http://diveintohtml5.info/history.html

Setting For Relative Links

  • To link around your application using relative links, you will need to set the <base> in the <head> of your document. This may be in the root index.html file of your Angular app. Find the <base> tag, and set it to the root URL you'd like for your app.

For example: <base href="/">

  • There are plenty of other ways to configure this, and the HTML5 mode set to true should automatically resolve relative links. If your root of your application is different than the url (for instance /my-base, then use that as your base.

Fallback for Older Browsers

  • The $location service will automatically fallback to the hashbang method for browsers that do not support the HTML5 History API.
  • This happens transparently to you and you won’t have to configure anything for it to work. From the Angular $location docs, you can see the fallback method and how it works.

In Conclusion

  • This is a simple way to get pretty URLs and remove the hashtag in your Angular application. Have fun making those super clean and super fast Angular apps!
Mr Lister
  • 42,557
  • 14
  • 95
  • 136
zero_cool
  • 2,948
  • 3
  • 33
  • 41
4

Using HTML5 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). Requiring a <base> tag is also important for this case, as it allows AngularJS to differentiate between the part of the url that is the application base and the path that should be handled by the application. For more information, see AngularJS Developer Guide - Using $location HTML5 mode Server Side.


Update

How to: Configure your server to work with html5Mode1

When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites. Here are some examples:

Apache Rewrites

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

Nginx Rewrites

server {
    server_name my-app;

    index index.html;

    root /path/to/app;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

Azure IIS Rewrites

<system.webServer>
  <rewrite>
    <rules> 
      <rule name="Main Rule" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

Express Rewrites

var express = require('express');
var app = express();

app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));

app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname });
});

app.listen(3006); //the port you want to use

See also

georgeawg
  • 46,994
  • 13
  • 63
  • 85
3

If you are wanting to configure this locally on OS X 10.8 serving Angular with Apache then you might find the following in your .htaccess file helps:

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On
    RewriteBase /~yourusername/appname/public/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !.*\.(css|js|html|png|jpg|jpeg|gif|txt)
    RewriteRule (.*) index.html [L]
</IfModule>

Options +FollowSymlinks if not set may give you a forbidden error in the logs like so:

Options FollowSymLinks or SymLinksIfOwnerMatch is off which implies that RewriteRule directive is forbidden

Rewrite base is required otherwise requests will be resolved to your server root which locally by default is not your project directory unless you have specifically configured your vhosts, so you need to set the path so that the request finds your project root directory. For example on my machine I have a /Users/me/Sites directory where I keep all my projects. Like the old OS X set up.

The next two lines effectively say if the path is not a directory or a file, so you need to make sure you have no files or directories the same as your app route paths.

The next condition says if request not ending with file extensions specified so add what you need there

And the [L] last one is saying to serve the index.html file - your app for all other requests.

If you still have problems then check the apache log, it will probably give you useful hints:

/private/var/log/apache2/error_log
Mister P
  • 1,143
  • 10
  • 9
  • If you use MAMP as your localhost apache server make sure the first RewriteBase is a relative link. e.g. RewriteBase /angularjs_site_folder/ – David Douglas May 29 '15 at 08:09
1

In Angular 6, with your router you can use:

RouterModule.forRoot(routes, { useHash: false })
gpresland
  • 1,169
  • 2
  • 14
  • 27
0

You could also use the below code to redirect to the main page (home):

{ path: '', redirectTo: 'home', pathMatch: 'full'}

After specifying your redirect as above, you can redirect the other pages, for example:

{ path: 'add-new-registration', component: AddNewRegistrationComponent},
{ path: 'view-registration', component: ViewRegistrationComponent},
{ path: 'home', component: HomeComponent}
Gharibi
  • 89
  • 8
0

**

It is recommended to use the HTML 5 style (PathLocationStrategy) as location strategy in Angular

** Because

  1. It produces the clean and SEO Friendly URLs that are easier for users to understand and remember.
  2. You can take advantage of the server-side rendering, which will make our application load faster, by rendering the pages in the server first before delivering it the client.

Use Hashlocationstrtegy only if you have to support the older browsers.

Click here to know more

Mahendra Waykos
  • 600
  • 2
  • 7
  • 17