2

I want to add www in front of the sub-domain which was created dynamically. The subdomain was created using *.example.com in the cpanel, so that user can create their own sub-domain through front-end.

I have added this code in .htaccess to direct my domain to https://www.example.com. But this doesn't work with subdomain.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule (.*) https://example.com/$1 [L,R=301]

How do I rewrite the code so that when using www.subdomain.example.com it can directs to subdomain.example.com? Without affecting my main domain name. My main domain and sub domain both will have www redirect.

G.Cloud
  • 23
  • 3
  • do you want to remove www from sub domain and force https as well ? – Mohammed Elhag Apr 09 '18 at 03:50
  • @Mohammed Elhag I want to enable www in front of subdomain. The user can use either www.subdomain.example.com or subdomain.example.com to view the website. – G.Cloud Apr 09 '18 at 03:58

1 Answers1

0

Use regular expression to match the subdomain, and use RewriteCond backreference to redirect back the users:

RewriteCond %{SERVER_PORT} 80 
RewriteCond %{HTTP_HOST} ^([^\.]+)\.example\.com [NC]
RewriteRule ^(.*)$ https://%1.example.com/$1 [R=301,L]

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

[^\.]+ matches one or more characters except dot (.) character. %1 is RewriteCond backreference that provide access to the grouped part ([^\.]+).

Ben
  • 5,069
  • 4
  • 18
  • 26
  • Will this affect the main domain? Sorry, I don't have much knowledge on .htaccess – G.Cloud Apr 09 '18 at 06:41
  • I just need to add this code below my existing code? My main domain and subdomain, both need to enable www in front of them. – G.Cloud Apr 10 '18 at 02:47
  • can you clarify your question what is the expected result for your main domain and subdomain, and give example. – Ben Apr 10 '18 at 04:01
  • The user can use www.subdomain.example.com to view subdomain.example.com, and www.example.com to view example.com. – G.Cloud Apr 10 '18 at 08:49
  • The current .htaccess allow the www.example.com direct to example.com, but not allow www.subdomain.example.com to direct to subdomain.example.com. I want the main domain and sub-domain can direct to their destination with www. – G.Cloud Apr 10 '18 at 08:50
  • https://stackoverflow.com/questions/13977851/htaccess-redirect-to-https-www – Ben Apr 10 '18 at 17:07
  • Thanks for the link. I will check it. – G.Cloud Apr 11 '18 at 08:05
  • I get the result by adding this few code under the existing code. Thanks. – G.Cloud Apr 17 '18 at 09:06