Jinesh Gandhi
Jinesh Gandhi

Reputation: 77

Remove "WWW" from "{HTTP_HOST}" in htaccess rules

I have 3 urls and have ssl certification

1) www.example.com

2) myexample.com

3) otherexample.com

I need to redirect all above three urls to https secure url e.g. : when user open any one above url it should redirect to https url.

=> when user open www.example.com OR example.com >>> it should redirect to https://www.example.com
=> when user open www.myexample.com OR myexample.com OR https://www.myexample.com >>> it should redirect to https://myexample.com
=> when user open www.otherexample.com OR otherexample.com OR https://www.otherexample.com >>> it should redirect to https://otherexample.com

Note : I have ssl certificat for www.example.com,myexample.com(non-www),otherexample.com(non-www)

I need help to solve my problem. also I want to set rules dynamically so in future if I have more url(s) so will not edit .htaccess file. (If possible to remove "www" from {HTTP_HOST} set rules below so It would good for me)

I have set coupule of rules in htaccess but it doesn't work for me.

RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}$1 [R=301,L]

#rule for myexample.com
RewriteEngine On
RewriteCond %{HTTP_HOST}  ^www.example.com [nocase]
RewriteRule ^(.*)         https://example.com/$1 [last,redirect=301]

#rule for otherexample.com
RewriteEngine On
RewriteCond %{HTTP_HOST}  ^www.otherexample.com [nocase]
RewriteRule ^(.*)         https://otherexample.com/$1 [last,redirect=301]

Upvotes: 3

Views: 2564

Answers (2)

Amit Verma
Amit Verma

Reputation: 41249

Try the following :

RewriteEngine on

#redirect any other domain that is not "www.example.com" to "https://"
RewriteCond %{HTTPS} off 
RewriteCond %{HTTP_HOST} (?:www\.)?((?!example\.com).+)$
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]
#redirect  "www.example.com" to "https://www"
RewriteCond %{HTTPS} off 
RewriteCond %{HTTP_HOST} (?:www\.)?((example\.com).+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]

Upvotes: 0

Mousami Roul
Mousami Roul

Reputation: 284

I hope it will work for you.

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

Upvotes: 3

Related Questions