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.
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 ([^\.]+)
.