Redirect non www to www http:// and https://

Redirect non www to www http:// and https://

I was on the search today to figure out how to redirect all traffic from a non-www address to a www address and also keep the SSL in the redirect using htaccess.
The following code will allow this to work.

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

So if you visit mydomain.com it will redirect to http://www.mydomain.com
If you visit https://mydomain.com it will redirect you https://www.mydomain.com
If you visit subdomain.mydomain.com it will NOT redirect you to http://www.subdomain.mydomain.com

Pretty cool right? I hope this can help someone else out as well.


About the Author

Chad

Freelance web developer and designer residing in Pittsburgh, PA I enjoy creating custom applications and websites to solve real-world problems. When I am not coding away I enjoy trying new craft beers from around the world.

Leave a Reply

New Blog Post: MySQL Using the JOIN Operand Within a Query - http://goo.gl/KHUij