Angular 2+ – Set base href dynamically

The marked answer here did not solve my issue, possibly different angular versions. I was able to achieve the desired outcome with the following angular cli command in terminal / shell:

ng build --base-href /myUrl/

ng build --bh /myUrl/ or ng build --prod --bh /myUrl/

This changes the <base href="https://stackoverflow.com/"> to <base href="https://stackoverflow.com/myUrl/"> in the built version only which was perfect for our change in environment between development and production. The best part was no code base requires changing using this method.


To summarise, leave your index.html base href as: <base href="https://stackoverflow.com/"> then run ng build --bh ./ with angular cli to make it a relative path, or replace the ./ with whatever you require.


Update:

As the example above shows how to do it from command line, here is how to add it to your angular.json configuration file.

This will be used for all ng serving for local development

"architect": {
    "build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "baseHref": "/testurl/",

This is the config specific for configuration builds such as prod:

"configurations": {
   "Prod": {
     "fileReplacements": [
        {
          "replace": src/environments/environment.ts",
          "with": src/environments/environment.prod.ts"
        }
      ],
      "baseHref": "./productionurl/",

The official angular-cli documentation referring to usage.

Leave a Comment