Forwarding all non-www to www

Hi, what’s the best way to forward all non-www (naked) traffic to the www subdomain whilst keeping url parameters intact? I am on gigalixir if that restricts (or simplifies anything) and my dns A record points to the ip provided by gigalixir, but I’d like to manage this within Elixir/Phoenix rather than at the dns level.

I am thinking along the lines of a plug, and some check on the subdomain part of but I don’t know where to actually apply the redirect outside of controllers.

Thanks for any help or light you can shed on this.

1 Like

Could you explain why you would like to do this at the application level?

I always understood it as being, usually, that general domains and subdomains should be defined at the DNS record level and only do application level redirects when the subdomains are accessed through the same virtual/physical server, but you have some “user” based subdomain going on (or similar) - I might be wrong but perhaps explaining why some other more knowledgeable folks might help you?

Not OP but I’ve always done this kind of redirection in apache or nginx, and it would be nice to know how to get rid of them if the beam can handle it all just as well.

My particular use-case is white-labelling the app, letting users or tenants create their own <tenant> so it appears like the site is their own. This could be managed with a wildcard DNS record at the DNS level and then let the app either internally route on subdomain or show views based on subdomain/user settings (my current setup)

Actually, I should change the title of this post to just forward the non-www/naked subdomain, not all non-www subdomains if there was confusion… but I would like to know how and where to do the redirect, without using the controllers. Instinctively I think it should be in a plug, just not sure how.

I’d imagine you could just redirect inside the plug then halt it to prevent further processing down the plug line?

1 Like

I’d go with nginx here. If you really really want to keep your logic on elixir side, do as @OvermindDL1 said, create plug that checks out suff in @conn and does redirect + halt

1 Like

Thanks, redirect seems the way to go.

1 Like

Just out of interest, how would this be configured in Cowboy vs nginx?