AlFra AlFra - 1 year ago 76
Apache Configuration Question

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

file. I've redirected
non www
urls to
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:
should redirect to
should still be
and should not redirect to

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

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

PS: Is there a possibility to take https into account.

Thank you in advance for your answers!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download