To those that use Fly.io for your Phoenix app - how did you configure nonwww and www domains in your DNS?

Here’s what my DNS settings look like at the moment on Namecheap.

And in my endpoint I’m only listening to the www domain and that www domain works. But when I visit the nonwww I want to redirect to the www endpoint.

config :my_app, MyAppWeb.Endpoint,  
  url: [host: "www.myapp.com", port: 80],

Render has pretty clear instructions on how to do this and it works fine.

Does anyone have tips for Fly.io? Thank you

I wanted the reverse and did:
DNS:
myapp.com
a & aaaa

www.myapp.com
cname myapp.com

myapp.co
a & aaaa

www.myapp.co
cname myapp.com

Everything becomes myapp.com

mix.exs (add dep)

...
      {:plug_canonical_host, "~> 2.0"}
...

config/runtime.exs

...
  host = System.get_env("PHX_HOST") || "myapp.com"
  port = String.to_integer(System.get_env("PORT") || "4000")

  # flyctl secrets set CANONICAL_HOST=myapp.com
  config :myapp,
    canonical_host: host

  config :myapp, MyappWeb.Endpoint,
...

lib/myapp_web/endpoint.ex

...
  socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]

  plug(:canonical_host)
...
  plug Plug.MethodOverride
  plug Plug.Head
  plug Plug.Session, @session_options
  plug MyappWeb.Router

  defp canonical_host(conn, _opts) do
    opts = PlugCanonicalHost.init(canonical_host: Application.get_env(:myapp, :canonical_host))
    PlugCanonicalHost.call(conn, opts)
  end
...

My app is generated using Phoenix 1.7.0-rc.0
I also use fly

Hope this helps u.

1 Like

An option is: https://redirect.pizza/

Does anybody still use the www. subdomain? At my job we never cared about the www for all the services we have deployed.

I used to redirect www to the root domain, but now default to using www.

https://jacob.hoffman-andrews.com/README/why-you-need-a-www/

When you host your site on example.com, you ideally to set an authentication cookie that gets sent to ‘example.com’ and not any subdomains. It turns out it’s impossible to do this in a cross-browser way. On most browsers, sending a Set-Cookie header without a domain field will do the trick. However, Internet Explorer differs on this point, and will send the cookie to all subdomains (see Q3).

I don’t want to put my hand in fire, but I don’t think this is the case anymore, moreover internet explorer is history by now.

I think you’re right. I just tested in Edge at setcookie.net, and (when not specifying domain) the browser didn’t send a root domain-set cookie for a subdomain request. When specifying setcookie.net or .setcookie.net, it did.

I still like to keep a public website at www, even if it’s unlikely many will be using Internet Explorer. :slight_smile:

Edit: that site has info on when IE and Edge behaviour in this regard changed: Cookie Quirks