Apache redirect non-www to www while keeping http and https intact

4 Comments

Topics: Hacks

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.

Email This Post Email This Post   | Print This Post Print This Post


Previous post in this category:

Posted on Thursday, August 16th, 2007

  • S

    The trick is to have two separate vhosts with a different rewrite rule in each as follows:

    1) for simpli.biz / *.simpli.biz port 80
    – rewrite to https://www.simpli.biz/$1

    2) for simpli.biz port 443
    – rewrite to https://www.simpli.biz/$1

    That’s it.

  • Anonymous

    Slightly OT: There’s just something incredibly sexy about a geek chick.

  • http://evilhomestereo.net/ Malte

    There’s a simpler ruleset which worked for me once upon a time (I actually used it to strip off the www but the needed changes should be obvious):

    RewriteRule ^ – [E=via:http]
    RewriteCond %{HTTPS} =on
    RewriteRule ^ – [E=via:https]
    RewriteCond %{HTTP_HOST} =www.(msquadrat.de) [NC]
    RewriteRule ^(.*)$ %{ENV:via}://%1/$1 [R=301]

  • http://www.pinkuin.com ram

    Hi,

    My site is http://www.pinkuin.com. without www it is not working how to redirect it this is in .htm & .htaccess file seem like hidden in ftp.

    Please help me