1
votes

i want set the domain like below:

example.com -> www.example.com

example.com/page -> www.example.com/page

www.example.com -> does not redirect

www.example.com/page -> does not redirect


subdomain.example.com -> does not redirect

subdomain.example.com/page -> does not redirect

www.subdomain.example.com -> subdomain.example.com

www.subdomain.example.com/page -> subdomain.example.com/page


http and https also should work.

I get the code from .htaccess to require WWW for domain, but allow subdomain if existing with no hard coding

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

it can work very well for all, but except below:

www.subdomain.example.com -> www.subdomain.example.com

www.subdomain.example.com/page -> www.subdomain.example.com/page

the subdomain should not have 'www.' prefix but it still with 'www.' prefix.

thanks for tutorial.

1

1 Answers

1
votes

Add this after the rules you have

RewriteCond %{HTTPS} ^on$
RewriteCond %{HTTP_HOST} ^www\.([^.]+\.[^.]+\.[^.]+)$
RewriteRule ^ https://%1%{REQUEST_URI} [L]

RewriteCond %{HTTPS} !^on$
RewriteCond %{HTTP_HOST} ^www\.([^.]+\.[^.]+\.[^.]+)$
RewriteRule ^ http://%1%{REQUEST_URI} [L]

I haven't tested it out, but I'm pretty sure my theory's solid on it. At least assuming the HTTPS part from your example works.