1

I am looking for a working solution for the following problem:

I have many domains with same website.

When somebody goes to www.domainname.tld there should be redirection to http://www.domainname.tld

When somebody goes to subdomain.domainname.tld there should be redirection to http://www.domainname.tld

When somebody goes to domainname.tld there should be redirection to http://www.domainname.tld.

===========================

I tried the following:

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule (.*) http://www.%{SERVER_NAME}/$1 [L,R=301]

===========================

Problem: When entering subdomain.domainname.tld there is redirection to www.subdomain.domainname.tld

===========================

I want it to be in .htaccess please.

I have searched already, but unfortunately without success.

I would be very happy if anybody could provide a solution :)

===========================

With your help I was able to change the code to:

RewriteCond %{HTTP_HOST} ^([^/.]+)\.(.*)\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%2\.%3/$1 [L,R=301]

I just would need a last change -> it should not direct to http://domain.tld -> I would prefer http://www.domain.tld

I have tried different attempts to add the www in the target - but without any success.

I ended with the Anonymous solution, which works well for me:

RewriteCond %{HTTP_HOST} !^www\.[^.]+\.[^.]+$
RewriteCond %{HTTP_HOST} ([^.]+\.[^.]+)$
RewriteRule (.*) http://www.%1/$1 [L,R=301]

Thanks to all who had time to read and help!

Telefonix
  • 13
  • 4
  • Possible duplicate of [.htaccess Redirect Subdomain to External URL](https://stackoverflow.com/questions/13989162/htaccess-redirect-subdomain-to-external-url) – technogeek1995 Aug 29 '19 at 16:13
  • I have not found solution with parameters only with fixed URL in it. – Telefonix Aug 29 '19 at 18:31
  • Possible duplicate of [Redirect wildcard subdomain without known domain - htaccess](https://stackoverflow.com/questions/51728083/redirect-wildcard-subdomain-without-known-domain-htaccess) – misorude Aug 30 '19 at 08:39

1 Answers1

0

There’s no way to remove all subdomains, but you can get the last two parts of the domain name:

RewriteCond %{HTTP_HOST} !^www\.[^.]+\.[^.]+$
RewriteCond %{HTTP_HOST} ([^.]+\.[^.]+)$
RewriteRule (.*) http://www.%1/$1 [L,R=301]
Anonymous
  • 11,748
  • 6
  • 35
  • 57
  • This works fine for redirecting subdomain.domain.tld to -> http://www.domain.tld - thank you. Also it works fine for keeping www.domain.tld when entered. The only thing not working is when entering www.subdomain.domain.tld -> than it is keeping whole URL. THANKS. – Telefonix Aug 30 '19 at 13:32
  • @Telefonix The updated answer should work for that. – Anonymous Aug 30 '19 at 13:53
  • Thanks @Anonymous I have decided to use your solution :) it seems that I can also switch easily to https when certificates are set ready :) – Telefonix Aug 30 '19 at 14:30
  • No problem. Glad I could help. – Anonymous Aug 30 '19 at 16:07