简体   繁体   中英

Redirect non-www to www except subdomains by .htaccess

There are a few questions like this, but my question is a little different

Redirect non-www to www in .htaccess

force non www to www in htaccess

Redirect Non-WWW to WWW URLs

I want to redirect the non-www version of the website to www, but it should not in any way effect the subdomains, so

www.example.com => www.example.com
example.com => www.example.com
sub1.example.com => sub1.example.com
sub2.example.com => sub2.example.com

this does not work, cause it does not behave good in case of subdomains

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

This solution works fine

RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) https://www.example.com/$1 [R=301,L] 

however, the important thing is I do not want to hardcode the domain name in htacess. How to (if even possible) have the above mentioned redirections for general case - without mentioned the exact domain name ?

Thanks

You can use this rule:

RewriteCond %{HTTP_HOST} ^[^.]+\.com(\.au)?$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM