How can I redirect subdomains in .htaccess to www. with generic parameters?

夙愿已清 提交于 2021-02-10 16:40:59

问题


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!


回答1:


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]


来源:https://stackoverflow.com/questions/57714019/how-can-i-redirect-subdomains-in-htaccess-to-www-with-generic-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!