52

Is it possible to add a base url to all routes in an AngularJS app? Essentially changing its location on the server (kind of, if that makes sense... so it would be accessed not via / but via /something/).

To add some context, I am trying to place an existing Angular app behind some authentication such that the app would now be accessed at address say http://mysite/secure after successful login.

The problem is if I was to load the app at http://mysite/secure it works fine (the server will obviously serve up the correct page), but clicking any link would result in a page reload and route to http://mysite/#newpage instead of http://mysite/secure/#newpage.

Without adding /secure/ to all of the routes and link element is this possible? Cheers, sorry if that is not worded well.

Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94
adamK
  • 3,849
  • 5
  • 37
  • 49
  • possible duplicate of [How to set root location for AngularJS router?](http://stackoverflow.com/questions/17319715/how-to-set-root-location-for-angularjs-router) – Jim G. Oct 13 '14 at 20:10

2 Answers2

40

The location for the base href must have trailing /. For example:

<base href="location" />

will not work. It must be in this format:

<base href="location/" />
Dennis Kiesel
  • 1,902
  • 3
  • 15
  • 20
38

Setting the <base> HTML5 tag might help. From the documentation here:

Relative links

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.

Running Angular apps with the History API enabled from document root is strongly encouraged as it takes care of all relative link issues.

Community
  • 1
  • 1
David Pope
  • 6,457
  • 2
  • 35
  • 45
  • 1
    I tried setting the tag but could not get it to work, the example in the docs appears not even to use it. Based on the second paragraph above, can I conclude, if not for the work required to update all links in my case, that including the additional route value would be better than trying to set a 'global' base url? – adamK Jul 21 '13 at 04:35
  • To update all the link, could be useful have a global constant declared with angular and accessible in all pages. http://stackoverflow.com/a/17505414/574147 – Fabio Bonfante Jul 21 '13 at 15:29
  • I have a which works well for almost everything. However, I added an additional reference, so I am doing an import as follows: import { FileUploadModule } from 'primeng/fileupload'; Everything seems to work in Visual Studio, but on running it, I get: GET http://localhost:59911/src/primeng/fileupload 404 (Not Found) Is this because of the base tag? Is there any way to get the import to ignore the base tag and just look in node_modules as it should? – Mike Mar 08 '18 at 20:15