1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00

Redirect to canonical domain

This commit is contained in:
Daniel Barber 2018-09-10 20:21:48 -04:00
parent a39a7e7cc9
commit 4982707355
Signed by: danbarber
GPG Key ID: 931D8112E0103DD8
3 changed files with 33 additions and 1 deletions

View File

@ -7,7 +7,7 @@ config :chess, ChessWeb.Endpoint,
root: "./assets",
secret_key_base: "${SECRET_KEY_BASE}",
server: true,
url: [host: "localhost", port: {:system, "PORT"}],
url: [host: "${HOST}", port: {:system, "PORT"}],
version: Application.spec(:chess, :vsn)
config :chess, Chess.Mailer,

View File

@ -23,6 +23,10 @@ defmodule ChessWeb.Endpoint do
plug Phoenix.CodeReloader
end
if Mix.env == :prod do
plug ChessWeb.Plugs.CanonicalDomain
end
plug Plug.RequestId
plug Plug.Logger

View File

@ -0,0 +1,28 @@
defmodule ChessWeb.Plugs.CanonicalDomain do
@moduledoc false
import Plug.Conn
def init(options) do
options
end
def call(conn, _options) do
if conn.host != canonical_host() do
conn
|> put_status(:moved_permanently)
|> Phoenix.Controller.redirect(external: canonical_domain(conn))
|> halt()
else
conn
end
end
defp canonical_domain(conn) do
"//#{canonical_host()}#{conn.request_path}"
end
defp canonical_host() do
ChessWeb.Endpoint.config(:url)[:host]
end
end