Strayer
Dynamically overriding static_url based on clients Host header
I have a Phoenix application that should be accessible in the local network and remotely via a reverse proxy. This means I can’t configure a URL in the Endpoint config, since the client did either use something like hostname.local or reverseproxy.example.tld.
I can easily override the Router URL with a simple Plug that calls Phoenix.Controller.set_router_url/2:
def set_router_url_by_host_header(conn, _opts) do
allowed_hosts = Application.get_env(:my_app, :allowed_hosts, [])
requested_host = conn.host
if requested_host in allowed_hosts do
Phoenix.Controller.put_router_url(conn, requested_host)
else
conn
end
end
This can’t be done for URLs generated with Routes.static_path though, since they always use the url or static_url configured in the Application env.
As far as I can see there is nothing to override this behavior with a plug, or am I missing something here?
Related StackOverflow question: https://stackoverflow.com/questions/52091185/how-can-i-configure-phoenix-to-use-the-clients-host-header-as-a-base-url-for-sta
Most Liked
easco
A Phoenix application can have more than one Endpoint. Can you use one for each of the domains you are supporting? You will have to run the endpoints on different ports, but you should be able to use the reverse proxy on the remote network to hide that.
LostKobrakai
I knew this is the case for the path helpers, but it seems to be missing for the static path helpers. Probably because it needs to know where to mount static assets from the endpoint itself.
But I just notices if the domain is really unknown just using a plain path should really be the solution.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









