Reputation: 2521
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?
Upvotes: 225
Views: 190035
Reputation: 48948
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.
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:
<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>
server {
server_name my-app;
index index.html;
root /path/to/app;
location / {
try_files $uri $uri/ /index.html;
}
}
<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>
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
Upvotes: 4
Reputation: 1819
In Angular 6, with your router you can use:
RouterModule.forRoot(routes, { useHash: false })
Upvotes: 1
Reputation: 677
**
It is recommended to use the HTML 5 style (PathLocationStrategy) as location strategy in Angular
** Because
Use Hashlocationstrtegy only if you have to support the older browsers.
Upvotes: 0
Reputation: 89
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}
Upvotes: 0
Reputation: 4254
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 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
<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="/">
Fallback for Older Browsers
In Conclusion
Upvotes: 12
Reputation: 10421
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.
Upvotes: 47
Reputation: 10997
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
Upvotes: 39
Reputation: 940
try
$locationProvider.html5Mode(true)
More info at
$locationProvider
Using $location
Upvotes: 31
Reputation: 46543
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
Upvotes: 267
Reputation: 1273
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
Upvotes: 3