Redirect non-www to www through secure connection (https/ssl)

June 8, 2014 7.9k views
Hi, I want to redirect http://domain.com to https://www.domain.com? I succeeded in redirecting http to https like this (in default-ssl.conf file):
<VirtualHost domain.com:80>
        RewriteEngine on
        ReWriteCond %{SERVER_PORT} !^443$
        RewriteRule ^/?(.*) https://%{HTTP_HOST}/$1 [NC,R,L]

</VirtualHost>

 <VirtualHost _default_:443>
         RewriteEngine on
         ServerAdmin webmaster@localhos
         ServerName domain.com:443
         ServerAlias www.domain.com
         DocumentRoot /var/www/html
this works fine until I type my domain without www, then I get the error message "this site is untrusted, the certificate is only valid to www.domain.com" My environment: - Ubuntu 14.04 - Apache2 - SSL issued for www.domain.com (common name) will appreciate you help thanks,
4 Answers
note:
the default-ssl.conf is:

""
RewriteEngine on
ReWriteCond %{SERVER_PORT} !^443$
RewriteRule ^/?(.*) https://%{HTTP_HOST}/$1 [NC,R,L]
""

""
RewriteEngine on
ServerAdmin webmaster@localhost
ServerName domain.com:443
ServerAlias www.domain.com
DocumentRoot /var/www/html
""
sorry the post does not accept programatic brackets. so first block of code is for
VirtualHost domian.com:80

the second block is for
VirtualHost _default_:443
I found the solution, for the people who suffered as me in finding a solution.. here is the answer:

VirtualHost domain.com:80

RewriteEngine on
ReWriteCond %{SERVER_PORT} !^443$
RewriteRule ^/?(.*) https://%{HTTP_HOST}/$1 [NC,R,L]

VirtualHost _default_:443

ServerAdmin webmaster@localhost
ServerName domain.com:443
ServerAlias www.domain.com
DocumentRoot /var/www/html
RewriteEngine on
RewriteCond %{HTTP_HOST} !^(www\.)?(.+)
RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]

Enjoy!

Why not simply:


NameVirtualHost *:80
<VirtualHost *:80>
   ServerName www.domain.com
   Redirect permanent / https://secure.domain.com/
</VirtualHost>

<VirtualHost _default_:443>
   ServerName secure.domain.com
   DocumentRoot /var/www/html
   SSLEngine On
# etc...
</VirtualHost>
Have another answer? Share your knowledge.