HTML 5 routing with Angular Cli on Ng server

If you are using Html 5 routing with old browsers (IE 11), probably you need special server side configuration (I am using this on IIS), . This article shows how to setup developer server routing in Angular Cli.

Using Angular Proxy to Backend

The Angular4 Cli is running on webpack dev server. Anyway Angular Cli natively supports only Proxy to backend configuration. It allows to setup which url pattern is being redirected internally by webserver. The configuration also allows to (redirect for example to localhost) and rewrite according to regex rules (provided by http=proxy=middleware module. The ng server needs configuration file, for example proxy.config.json and start ng serve with special parameter –proxy-config  to load configuration file.

The proxy.config.json file can look like this:

  "/": {
    "pathRewrite": {"^/(.+)": "/"},
    "target": "http://localhost:4200",
    "secure": false,
    "logLevel": "debug"

The first line (with “/”) is asking to redirect all requests according to configuration in block.

The pathRewrite is doing to actual work. It changes url, which starts with / followed by some characters. The even better version could exclude strings with . (dot) like icon.gif from redirection, but this works well. Whatever is in form of slash and characters will be send to root “/” on server.

The target is the remote server, where your request is being proxied. It turns out this is required option. The original intent is to allow resending for example /api to another server. For our use we can use same server which ng server is hosting. In this case localhost.

To start ng server, with the config file use following argument:

ng serve --host localhost --proxy-config proxy.config.json --env dev --open

Common issues

If proxy doesnt work, verbose dev logging can be used to show redirections. Also, at the start lf ng serve, you should see two lines like:
[HPM] Proxy created: / -> http://localhost
[HPM] Proxy rewrite rule created: "^/(.+)" ~> "/"

Hopefully it helps.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s