View Source CanonicalHost
Plug for redirecting all traffic to a canonical host.
Installation
The package can be installed by adding canonical_host to your list of dependencies in mix.exs:
def deps do
[
{:canonical_host, "~> 1.0"}
]
endUsage
# config/runtime.exs
config :canonical_host, :default, host: "https://myhost.com"# plug pipeline in router.ex or endpoint.ex
plug CanonicalHostMultiple canonical hosts
# config/runtime.exs
config :canonical_host, :one, host: "https://host-one.com"
config :canonical_host, :two, host: "https://host-two.com"# one plug pipeline
plug CanonicalHost, config_key: :one
# another plug pipeline
plug CanonicalHost, config_key: :twoAlternatives
plug_canonical_host
I chose to create a new library instead of using this library for the following reasons:
- Has awkward configuration. It is not convenient to configure at runtime. Instead, the README suggests that you write your own function plug and then call both
PlugCanonicalHost.init/1andPlugCanonicalHost.call/2in your function plug. - Redirects HTTP requests with methods other than
GET. Consider a case where an API client sends aPOSTrequest to your app at the non-canonical domain.PlugCanonicalHostwill cause the request to not be handled but will return an HTTP301response which would make the client believe that the request succeeded. - Tries to redirect with the same scheme (HTTP/HTTPS) and port number as the original request. I'd prefer to always redirect to the canonical scheme/host/port and save the user a possible extra redirect.