Apache redirect non-www to www while keeping http and https intact
I have no idea why this is so hard to find on the Internet, but it took me over an hour to piece together this solution.
Scenario: A client has a site where the SSL certificate has been purchased for www.[hisdomain].com, so https://hisdomain.com/ shows a certificate error. Also, for SEO purposes, he wants requests for http://[hisdomain].com to redirect to http://www.[hisdomain].com — if you don’t implement this in Apache, Google indexes [hisdomain].com and www.[hisdomain].com separately, with different PageRanks, so you don’t get the full benefit of those linking to your site.
Oddly, there are lots of tutorials on how to turn HTTP requests into HTTPS, and lots of tutorials on how to translate stuff from non-www to www, but no tutorials that combine the two. Using my regex skills and with some research, I figured out how to do this using mod_redirect in a .htaccess file. (Note that if you want to run this in httpd.conf, you have to add an extra / in the rewriterule lines. I want to slap whatever programmer decided two different syntaxes depending on where you locate the code was a good idea. Use a .htaccess to make this work properly.)
Options +FollowSymlinks
RewriteEngine On
rewritecond %{https} =off
RewriteCond %{HTTP_HOST} !^www\.simpli\.biz [nc]
rewritecond %{http_host} ^simpli\.biz [nc]
rewriterule ^(.*)$ http://www.simpli.biz/$1 [r=301,nc]
rewritecond %{https} =on
RewriteCond %{HTTP_HOST} !^www\.simpli\.biz [nc]
rewritecond %{http_host} ^simpli\.biz [nc]
rewriterule ^(.*)$ https://www.simpli.biz/$1 [r=301,nc]
Update: I tried this on another server and it only half worked… https://[domain] redirected to http://www.[domain]. But it works properly on the first server…so give it a shot, and if it doesn’t work for you, feel free to post what does.