AlFra
AlFra

Reputation: 419

Redirecting non-www to www, but keeping other sub-domains intact

I have 5 web pages with different domain names. Each of them uses the same directory and the same .htaccess file. I've redirected non www urls to www with this lines:

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

Now I would like to keep redirecting non wwws to wwws, but I would also like to keep other subdomains without www. For example: domain1.com should redirect to www.domain1.com and subdomain1.domain1.com should still be subdomain1.domain1.com and should not redirect to www.subdomain1.domain1.com.

Keep in mind I have 5 webpages hosted from the same directory and there are more to come. I don't want to change .htaccess file everytime there is a page added.

I don't want to mess up my .htaccess file so I need your help!

PS: Is there a possibility to take https into account. https://domain.com to https://www.domain.com http://domain.com to http://www.domain.com https://sub.domain.com to https://sub.domain.com http://sub.domain.com to http://sub.domain.com

Thank you in advance for your answers!

Upvotes: 1

Views: 44

Answers (1)

anubhava
anubhava

Reputation: 785246

Just target your rule for main domain:

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

RewriteCond %{HTTPS}s on(s)| and %1 is used to maintain http/https in target URL.

Make sure to clear your browser cache when testing this change.

Upvotes: 1

Related Questions