Search code examples
ms-yarp

yarp rewriting hardcoded service urls


I don't know, if my question is well formulated, but I try... I'm using yarp as a reverse proxy. Behind the proxy there is a asp.net core service (order-service) on port 5048 e.g.

So the config looks like the following:

"ReverseProxy": {
  "Routes": {
    "orderService": {
      "ClusterId": "orderServiceProps",
      "Match": {
        "Path": "/order-service/{**Remainder}"
      },
      "Transforms": [
        {
          "PathRemovePrefix": "/order-service"
        }
      ]
    }
  },
  "Clusters": {
    "orderServiceProps": {
      "Destinations": {
        "destination1": {
          "Address": "http://localhost:5048"
        }
      }
    }
  }
}

If I type e.g. http://localhost:8080/order-service/api/collection the request gets forwarded to http://localhost:5048/api/collection All well so far. But the order-service also has a simple html gui, which is showing some simple links to some special endpoints.
enter image description here

Now if I click on e.g. the settings link, the service navigates to http://localhost:5048/settings but I want the service navigates to http://localhost:8080/order-service/settings
I don't know if I can reach such a bahavior.
I don't want the user is seeing the 5048 in his browser!
And can I do this without let the service know that it is behind a proxy?


Solution

  • The problem is that your service creates links in HTML assuming it is running on localhost:5048, while from the browser perspective it is on different URL.

    I do not know the way to make it work without any change to your service, but it is possible with minimal change.

    First, make all your links relative, like <a href="settings"> instead of <a href="http://localhost:5048/settings"

    Then your link, when the user clicks it, will lead to http://localhost:8080/settings, which is not yet what you want, but at least the host:port address is correct.

    Second, when you render the HTML page (or serve it from a static file), add a base tag to HTML header, like this:

    <head>
       ...
       <base href="http://localhost:8080/order-service/">
       ...
    </head>
    

    This will make your base address added automatically to all the relative links at your page, so <a href="settings"> will lead to http://localhost:8080/order-service/settings, just as you want it to.

    As you can see, your service still has to be aware of the address it is accessed on, but it is localized in one place -- in the base tag.