Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop WWW for sub-domain with htaccess

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.com to www.example.com

anything.example.com to anything.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.

like image 418
shanmuga pradeep Avatar asked Jan 24 '23 04:01

shanmuga pradeep


1 Answers

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.

like image 66
anubhava Avatar answered Jan 29 '23 08:01

anubhava