Here is another way of proxying when you need more flexibility:
You can use the 'router' option and some javascript code to rewrite the target URL dynamically. For this, you need to specify a javascript file instead of a json file as the --proxy-conf parameter in your 'start' script parameter list:
"start": "ng serve --proxy-config proxy.conf.js --base-href /"
As shown above, the --base-href parameter also needs to be set to / if you otherwise set the <base href="..."> to a path in your index.html. This setting will override that and it's necessary to make sure URLs in the http requests are correctly constructed.
Then you need the following or similar content in your proxy.conf.js (not json!):
const PROXY_CONFIG = {
"/api/*": {
target: https://www.mydefaulturl.com,
router: function (req) {
var target = 'https://www.myrewrittenurl.com'; // or some custom code
return target;
},
changeOrigin: true,
secure: false
}
};
module.exports = PROXY_CONFIG;
Note that the router option can be used in two ways. One is when you assign an object containing key value pairs where the key is the requested host/path to match and the value is the rewritten target URL. The other way is when you assign a function with some custom code, which is what I'm demonstrating in my examples here. In the latter case I found that the target option still needs to be set to something in order for the router option to work. If you assign a custom function to the router option then the target option is not used so it could be just set to true. Otherwise, it needs to be the default target URL.
Webpack uses http-proxy-middleware so you'll find useful documentation there: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md#http-proxy-middleware-options
The following example will get the developer name from a cookie to determine the target URL using a custom function as router:
const PROXY_CONFIG = {
"/api/*": {
target: true,
router: function (req) {
var devName = '';
var rc = req.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
if(parts.shift().trim() == 'dev') {
devName = decodeURI(parts.join('='));
}
});
var target = 'https://www.'+ (devName ? devName + '.' : '' ) +'mycompany.com';
//console.log(target);
return target;
},
changeOrigin: true,
secure: false
}
};
module.exports = PROXY_CONFIG;
(The cookie is set for localhost and path '/' and with a long expiry using a browser plugin. If the cookie doesn't exist, the URL will point to the live site.)