my subdomain.example.com redirecting to www.subdomain.example.com.
Htaccess code :
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### END WWW & HTTPS
I am looking for
example.comtowww.example.com
anything.example.comtoanything.example.com
How can i fix this?
Update : i am using one htaccess file for both subdomain and root domain and i cannot use separate htaccess file for for different domain for a reason.
Note : please do not mark this question duplicate. i have already searched other part of stackoverflow and do not find a working solution.
CodePudding user response:
You need restrict your rewrite condition to match only top level domain:
# ensure www. to top level domain only
RewriteCond %{HTTP_HOST} ^[\w-] \.(com|net|in|co\.uk)$ [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### END WWW & HTTPS
Make sure to clear your browser cache before testing.
CodePudding user response:
Solution : https://stackoverflow.com/a/35285128/4643961
### START WWW & HTTPS
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# remove www if subdomain
RewriteCond %{HTTP_HOST} ^www\.([^.] \.[^.] \.[^.] )$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### END WWW & HTTPS
Alternative :
### START WWW & HTTPS
# add www if not subdomain
RewriteCond %{HTTP_HOST} ^[^.] \.[^.] $
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# remove www if subdomain
RewriteCond %{HTTP_HOST} ^www\.([^.] \.[^.] \.[^.] )$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### END WWW & HTTPS
