Skip to content

Instantly share code, notes, and snippets.

@xolan
Created July 18, 2018 11:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xolan/776e55356a9c45b93debe03ede82da2f to your computer and use it in GitHub Desktop.
Save xolan/776e55356a9c45b93debe03ede82da2f to your computer and use it in GitHub Desktop.
Handle X-Forwarded-Prefix with Plug.Traefik
defmodule Plug.Traefik do
use Plug.Builder
@assets_dir System.cwd <> "/priv/web/assets/"
plug Plug.Static, at: "/assets", from: @assets_dir
plug :x_forwarded_prefix
def x_forwarded_prefix(conn, _) do
register_before_send(conn, fn(conn) ->
case get_req_header(conn, "x-forwarded-prefix") do
[prefix] -> resp(conn, conn.status, replace(conn.resp_body, prefix))
[] -> conn
end
end)
end
defp replace(source, prefix) when is_bitstring(source) do
case String.starts_with?(source, "/") do
true ->
String.replace(source, "/", prefix <> "/", global: false)
false ->
source
|> String.replace("src=\"/", "src=\"" <> prefix <> "/")
|> String.replace("href=\"/", "href=\"" <> prefix <> "/")
end
end
defp replace(source, prefix) when is_list(source) do
source
|> Enum.map(fn item -> replace(item, prefix) end)
end
defp replace(source, _prefix) do
source
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment