Redirect 将Elixir Phoenix请求从根域重定向到www
我们在Heroku上有一个Phoenix应用程序,在53号公路上有DNS。我们根据这篇博文设置了正确的http到https重定向:Redirect 将Elixir Phoenix请求从根域重定向到www,redirect,heroku,elixir,phoenix-framework,Redirect,Heroku,Elixir,Phoenix Framework,我们在Heroku上有一个Phoenix应用程序,在53号公路上有DNS。我们根据这篇博文设置了正确的http到https重定向: 一切正常,剩下的就是将根重定向到子域www 有没有一种推荐的方法可以用Phoenix的方式进行设置?只需在应用程序端点顶部的重定向中进行设置 在lib/app/endpoint.ex中: defmodule App.Endpoint do use Phoenix.Endpoint, otp_app: :app socket "/socket", App.
一切正常,剩下的就是将根重定向到子域www 有没有一种推荐的方法可以用Phoenix的方式进行设置?只需在应用程序端点顶部的重定向中进行设置 在
lib/app/endpoint.ex
中:
defmodule App.Endpoint do
use Phoenix.Endpoint, otp_app: :app
socket "/socket", App.UserSocket
plug App.Plugs.WWWRedirect
# ...
end
defmodule App.Plugs.WWWRedirect do
import Plug.Conn
def init(options) do
options
end
def call(conn, _options) do
if bare_domain?(conn.host) do
conn
|> Phoenix.Controller.redirect(external: www_url(conn))
|> halt
else
conn # Since all plugs need to return a connection
end
end
# Returns URL with www prepended for the given connection. Note this also
# applies to hosts that already contain "www"
defp www_url(conn) do
"#{conn.scheme}://www.#{conn.host}"
end
# Returns whether the domain is bare (no www)
defp bare_domain?(host) do
!Regex.match?(~r/\Awww\..*\z/i, host)
end
end
在lib/app/plugs/www_redirect.ex
:
defmodule App.Endpoint do
use Phoenix.Endpoint, otp_app: :app
socket "/socket", App.UserSocket
plug App.Plugs.WWWRedirect
# ...
end
defmodule App.Plugs.WWWRedirect do
import Plug.Conn
def init(options) do
options
end
def call(conn, _options) do
if bare_domain?(conn.host) do
conn
|> Phoenix.Controller.redirect(external: www_url(conn))
|> halt
else
conn # Since all plugs need to return a connection
end
end
# Returns URL with www prepended for the given connection. Note this also
# applies to hosts that already contain "www"
defp www_url(conn) do
"#{conn.scheme}://www.#{conn.host}"
end
# Returns whether the domain is bare (no www)
defp bare_domain?(host) do
!Regex.match?(~r/\Awww\..*\z/i, host)
end
end
请注意,您需要重新启动服务器才能使其生效。您还可以使用来为您保管它,并确保您的Elixir应用程序只能通过其规范URL访问