defmodule PlugCanonicalHost do @moduledoc """ A Plug for ensuring that all requests are served by a single canonical host """ import Plug.Conn @location_header "location" @status_code 301 @html_template """
The document has moved here.
""" @doc """ Initialize this plug with a canonical host option. """ def init([canonical_host: canonical_host]), do: [canonical_host: canonical_host] @doc """ Call the plug. """ def call(conn = %Plug.Conn{host: host}, [canonical_host: canonical_host]) when is_nil(canonical_host) == false and canonical_host !== "" and host !== canonical_host do location = conn |> redirect_location(canonical_host) conn |> put_resp_header(@location_header, location) |> send_resp(@status_code, String.replace(@html_template, "%s", location)) |> halt end def call(conn, _), do: conn defp redirect_location(conn, canonical_host) do conn |> request_uri |> URI.parse |> Map.put(:host, canonical_host) |> URI.to_string end defp request_uri(conn) do "#{conn.scheme}://#{conn.host}:#{conn.port}#{conn.request_path}?#{conn.query_string}" end end