Idiomatic way to detect base url

What the idiomatic way to determine a webapp’s base URL on (i.e. I have a technique outlined below. Any suggestions to simplify my base url detection flow is appreciated.

  1. Get the URL scheme from the Fly-Forwarded-Proto header. It will likely be either http or https.
  2. Get the public facing hostname via the Host header. If you’re app in on the domain, it’ll look like
  3. Then check if the Fly-Forwarded-Port is the default port for the protocol scheme (i.e. 80 for http, 443 for https).
  4. Finally put together the base url like the following pseudocode: fly-forwarded-proto + '://' + host + (if scheme_default_port != fly-forwarded-port then ':' + fly-forwarded-port else '') + '/'