views:

760

answers:

1

I have an SSL certificate for the 'www' subdomain of a web site we'll call example.com.

Therefore I can force SSL, but if the user doesn't enter 'www.example.com' into their browser, the SSL certificate appears invalid.

I wish to accomplish this with mod_rewrite rules in an .htaccess file at the root of the web site.

No matter what URI the user enters, (e.g. example.com, www.example.com, https://example.com, example.com/folder/file.html, etc.), I want to force the HTTPS and the www subdomain, keeping whatever URI they provided, of course.

I was playing around with the .htaccess file and some rules, as I've already done some research, but I don't have much experience with mod_rewrite or .htaccess. I think I found the SVN revision that almost worked for me, but not quite. Here it is:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
RewriteCond %{HTTP_HOST} ^example.com [nc]
RewriteRule ^(.*)$ https://www.example.com/$1 [r=301,nc]

Try not to laugh too hard at my file; it is mostly derived from examples I found online.

Any pointers are appreciated! =)

+2  A: 

Try this:

RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301]
Gumbo
Modified from your original (which had %{HTTP_HOST} in the RewriteRule line, which I see you've already fixed) it works great: RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301]