How to redirect an domain to subdomain?

Hello,
I want to know how can i redirect an domain (example.com) to an subdomain (www.example.com) ?

I use docker bunkerweb-aio and the bunkerweb ui.

I have an service with SERVER_NAME = example.com www.example.com

In Redirect section i have set REDIRECT_FROM = / , REDIRECT_TO = https://www.example.com , REDIRECT_TO_REQUEST_URI = off , REDIRECT_TO_STATUS_CODE = 301

But it’s not work.
Maybe i need to declare an environment variable ? like example.com_REDIRECT_TO=https://www.example.com

Thank you for the help.

Hi,

The problem is that both names are in the same service. With SERVER_NAME = ``example.com`` ``www.example.com, the redirect applies to the whole service, including www.example.com, so it ends up trying to redirect the target to itself.

To make this work you need two separate services:

  1. Keep your main service for the app, but set its SERVER_NAME to www.example.com only. This is the one that actually serves your site.

  2. Create a second service with SERVER_NAME = example.com (the bare domain only) and put the redirect settings on that one:

REDIRECT_FROM = /
REDIRECT_TO = https://www.example.com
REDIRECT_TO_REQUEST_URI = yes
REDIRECT_TO_STATUS_CODE = 301

Set REDIRECT_TO_REQUEST_URI = yes if you want the path to carry over, so example.com/page lands on www.example.com/page. Leave it on no if you always want visitors to land on the root.

About the env variable: the example.com_REDIRECT_TO=... prefix only targets a service whose primary server name is example.com. Since your current service holds both names in one block, the prefix cannot single out the bare domain on its own, which is why splitting them into two services is the way to go.

One last thing, make sure example.com has a valid certificate (for example AUTO_LETS_ENCRYPT = yes on that second service) so the redirect works over HTTPS.

Hope that helps.