![](/img/trans.png)
[英]Redirect from the domain with www to the root domain - working but not completely properly
[英]Redirect Elixir Phoenix request from root domain to www
我们在Route 53上有一个关于Heroku的Phoenix应用程序和DNS。我们按照这篇博文来设置正确的http到https重定向:
http://building.vts.com/blog/2015/11/02/route53-ssl-naked-domain-redirect/
一切正常,剩下的就是将根重定向到子域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
在lib/app/plugs/www_redirect.ex
:
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
中的任何内容 。
您还可以使用plug_canonical_host
来为您处理它,并确保您的Elixir应用程序只能通过其规范URL访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.