Apache htaccess redirect https from non-www to www

.htaccessapache-2.2httpsredirect

How can I redirect from https://mysite.com to https://www.mysite.com?
The SSL certificate is bought for www.mysite.com and shows a warning if accessed without www.

Best Answer

It will be too late. Users will have already seen the error message and had to accept it by the time the redirect happens unless you get another certificate. The previous answer has that problem.

Ignoring that, you can create a named based virtual host on port 443, set up ssl on that, and then have it rewrite. Note that instead of using your existing certificate (which will generate an error) you can have a cheap, valid certificate under mysite.com on that virtual host so that you don't get an error prior to the redirect.

NameVirtualHost *:443
<VirtualHost *:443>
  ServerName myname.com
  SSLCertificateFile /etc/ssl/apache2/server.crt
  SSLCertificateKeyFile /etc/ssl/apache2/server.key
  SSLEngine on
  RewriteEngine on
  RewriteRule ^/(.*)  https://www.mysite.com%{REQUEST_URI}      [L,R]
</VirtualHost>