Skip to content
This repository has been archived by the owner on Apr 12, 2024. It is now read-only.

Commit

Permalink
fix($location): always resolve relative links in html5mode to `<base>…
Browse files Browse the repository at this point in the history
…` url

BREAKING CHANGE (since 1.2.0 and 1.3.0-beta.1):

Angular now requires a `<base>` tag when html5 mode of `$location` is enabled. Reasoning:
Using html5 mode without a `<base href="...">` tag makes relative links for images, links, ...
relative to the current url if the browser supports
the history API. However, if the browser does not support the history API Angular falls back to using the `#`,
and then all those relative links would be broken.

The `<base>` tag is also needed when a deep url is loaded from the server, e.g. `http://server/some/page/url`.
In that case, Angular needs to decide which part of the url is the base of the application, and which part
is path inside of the application.

To summarize: Now all relative links are always relative to the `<base>` tag.

Exception (also a breaking change):
Link tags whose `href` attribute starts with a `#` will only change the hash of the url, but nothing else
(e.g. `<a href="#someAnchor">`). This is to make it easy to scroll to anchors inside a document.

Related to #6162
Closes #8492

BREAKING CHANGE (since 1.2.17 and 1.3.0-beta.10):

In html5 mode without a `<base>` tag on older browser that don't support the history API
relative paths were adding up. E.g. clicking on `<a href="page1">` and then on `<a href="page2">`
would produce `$location.path()==='/page1/page2'. The code that introduced this behavior was removed
and Angular now also requires a `<base>` tag to be present when using html5 mode.

Closes #8172, #8233
  • Loading branch information
tbosch committed Aug 29, 2014
1 parent b9007df commit 2294880
Show file tree
Hide file tree
Showing 5 changed files with 204 additions and 134 deletions.
51 changes: 51 additions & 0 deletions docs/content/error/$location/nobase.ngdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
@ngdoc error
@name $location:nobase
@fullName $location in HTML5 mode requires a <base> tag to be present!
@description

If you configure {@link ng.$location `$location`} to use
{@ng.provider.$locationProvider `html5Mode`} (`history.pushState`), you need to specify the base URL for the application with a [`<base href="">`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base) tag.

The base URL is then used to resolve all relative URLs throughout the application regardless of the
entry point into the app.

If you are deploying your app into the root context (e.g. `https://myapp.com/`), set the base URL to `/`:

```html
<head>
<base href="/">
...
</head>
```

If you are deploying your app into a sub-context (e.g. `https://myapp.com/subapp/`), set the base URL to the
URL of the subcontext:

```html
<head>
<base href="/myapp">

This comment has been minimized.

Copy link
@gkalpak

gkalpak Sep 1, 2014

Member

Shouldn't this rather be href="/subapp" ?

This comment has been minimized.

Copy link
@tbosch

tbosch Sep 2, 2014

Author Contributor

Thanks. Yes, changed in master now.

...
</head>
```

Before Angular 1.3 we didn't have this hard requirement and it was easy to write apps that worked
when deployed in the root context but were broken when moved to a sub-context because in the
sub-context all absolute urls would resolve to the root context of the app. To prevent this,
use relative URLs throughout your app:

```html
<!-- wrong: -->
<a href="/userProfile">User Profile</a>


<!-- correct: -->
<a href="userProfile">User Profile</a>

```

Additionally, if you want to support [browsers that don't have the `history.pushState`
API](http://caniuse.com/#feat=history), the fallback mechanism provided by `$location`
won't work well without specifying the base url of the application.

In order to make it easier to migrate from hashbang mode to html5 mode, we require that the base
URL is always specified when `$location`'s `html5mode` is enabled.
22 changes: 12 additions & 10 deletions docs/content/guide/$location.ngdoc
Original file line number Diff line number Diff line change
Expand Up @@ -325,20 +325,22 @@ to URLs that should be handled with `.`. Now, links to locations, which are not
are not prefixed with `.` and will not be intercepted by the `otherwise` rule in your `$routeProvider`.


### Server side
### Relative links

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)
Be sure to check all relative links, images, scripts etc. Angular requires you to specify the url base in
the head of your main html file (`<base href="/my-base">`). With that, relative urls will
always be resolved to this base url, event if the initial url of the document was different.

### Relative links
There is one exception: Links that only contain a hash fragment (e.g. `<a href="#target">`)
will only change `$location.hash()` and not modify the url otherwise. This is useful for scrolling
to anchors on the same page without needing to know on which page the user currently is.

Be sure to check all relative links, images, scripts etc. You must either specify the url base in
the head of your main html file (`<base href="/my-base">`) or you must use absolute urls
(starting with `/`) everywhere because relative urls will be resolved to absolute urls using the
initial absolute url of the document, which is often different from the root of the application.
### Server side

Running Angular apps with the History API enabled from document root is strongly encouraged as it
takes care of all relative link issues.
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). Requiring a `<base>` tag is also important for
this case, as it allows Angular to differentiate between the part of the url that is the application
base and the path that should be handeled by the application.

### Sending links among different browsers

Expand Down
107 changes: 52 additions & 55 deletions src/ng/location.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,21 +127,32 @@ function LocationHtml5Url(appBase, basePrefix) {
this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
};

this.$$rewrite = function(url) {
this.$$parseLinkUrl = function(url, relHref) {
if (relHref && relHref[0] === '#') {
// special case for links to hash fragments:
// keep the old url and only replace the hash fragment
this.hash(relHref.slice(1));
return true;
}
var appUrl, prevAppUrl;
var rewrittenUrl;

if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
prevAppUrl = appUrl;
if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
} else {
return appBase + prevAppUrl;
rewrittenUrl = appBase + prevAppUrl;
}
} else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
return appBaseNoFile + appUrl;
rewrittenUrl = appBaseNoFile + appUrl;
} else if (appBaseNoFile == url + '/') {
return appBaseNoFile;
rewrittenUrl = appBaseNoFile;
}
if (rewrittenUrl) {
this.$$parse(rewrittenUrl);
}
return !!rewrittenUrl;
};
}

Expand Down Expand Up @@ -231,10 +242,12 @@ function LocationHashbangUrl(appBase, hashPrefix) {
this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
};

this.$$rewrite = function(url) {
this.$$parseLinkUrl = function(url, relHref) {
if(stripHash(appBase) == stripHash(url)) {
return url;
this.$$parse(url);
return true;
}
return false;
};
}

Expand All @@ -254,16 +267,28 @@ function LocationHashbangInHtml5Url(appBase, hashPrefix) {

var appBaseNoFile = stripFile(appBase);

this.$$rewrite = function(url) {
this.$$parseLinkUrl = function(url, relHref) {
if (relHref && relHref[0] === '#') {
// special case for links to hash fragments:
// keep the old url and only replace the hash fragment
this.hash(relHref.slice(1));
return true;
}

var rewrittenUrl;
var appUrl;

if ( appBase == stripHash(url) ) {
return url;
rewrittenUrl = url;
} else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
return appBase + hashPrefix + appUrl;
rewrittenUrl = appBase + hashPrefix + appUrl;
} else if ( appBaseNoFile === url + '/') {
return appBaseNoFile;
rewrittenUrl = appBaseNoFile;
}
if (rewrittenUrl) {
this.$$parse(rewrittenUrl);
}
return !!rewrittenUrl;
};

this.$$compose = function() {
Expand Down Expand Up @@ -626,14 +651,18 @@ function $LocationProvider(){
appBase;

if (html5Mode) {
if (!baseHref) {
throw $locationMinErr('nobase',
"$location in HTML5 mode requires a <base> tag to be present!");
}
appBase = serverBase(initialUrl) + (baseHref || '/');
LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
} else {
appBase = stripHash(initialUrl);
LocationMode = LocationHashbangUrl;
}
$location = new LocationMode(appBase, '#' + hashPrefix);
$location.$$parse($location.$$rewrite(initialUrl));
$location.$$parseLinkUrl(initialUrl, initialUrl);

var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;

Expand All @@ -652,6 +681,9 @@ function $LocationProvider(){
}

var absHref = elm.prop('href');
// get the actual href attribute - see
// http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
var relHref = elm.attr('href') || elm.attr('xlink:href');

if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
// SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
Expand All @@ -662,50 +694,15 @@ function $LocationProvider(){
// Ignore when url is started with javascript: or mailto:
if (IGNORE_URI_REGEXP.test(absHref)) return;

// Make relative links work in HTML5 mode for legacy browsers (or at least IE8 & 9)
// The href should be a regular url e.g. /link/somewhere or link/somewhere or ../somewhere or
// somewhere#anchor or http://example.com/somewhere
if (LocationMode === LocationHashbangInHtml5Url) {
// get the actual href attribute - see
// http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
var href = elm.attr('href') || elm.attr('xlink:href');

if (href && href.indexOf('://') < 0) { // Ignore absolute URLs
var prefix = '#' + hashPrefix;
if (href[0] == '/') {
// absolute path - replace old path
absHref = appBase + prefix + href;
} else if (href[0] == '#') {
// local anchor
absHref = appBase + prefix + ($location.path() || '/') + href;
} else {
// relative path - join with current path
var stack = $location.path().split("/"),
parts = href.split("/");
if (stack.length === 2 && !stack[1]) stack.length = 1;
for (var i=0; i<parts.length; i++) {
if (parts[i] == ".")
continue;
else if (parts[i] == "..")
stack.pop();
else if (parts[i].length)
stack.push(parts[i]);
}
absHref = appBase + prefix + stack.join('/');
}
}
}

var rewrittenUrl = $location.$$rewrite(absHref);

if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
event.preventDefault();
if (rewrittenUrl != $browser.url()) {
if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
if ($location.$$parseLinkUrl(absHref, relHref)) {
event.preventDefault();
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
if ($location.absUrl() != $browser.url()) {
$rootScope.$apply();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
}
}
}
});
Expand Down
4 changes: 4 additions & 0 deletions test/ng/anchorScrollSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ describe('$anchorScroll', function() {
return function($provide, $locationProvider) {
$provide.value('$sniffer', {history: config.historyApi});
$locationProvider.html5Mode(config.html5Mode);
$provide.decorator('$browser', function($delegate) {
$delegate.$$baseHref = '/';
return $delegate;
});
};
}

Expand Down
Loading

4 comments on commit 2294880

@winsontam
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can it add to 1.2.x version as well?

@tbosch
Copy link
Contributor Author

@tbosch tbosch commented on 2294880 Sep 2, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we will add this to 1.2.x as well. Just waiting for a little but to get all the regressions first...

@mllrjb
Copy link
Contributor

@mllrjb mllrjb commented on 2294880 Sep 11, 2014

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any update on when this will be added to 1.2.x?

@jhuntdog
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is great! Excited to see this come to 1.2.x.

Please sign in to comment.