for a while I've been struggeling with this problem and did not find a solution which satisfies all my needs. I have two sites, example.com and example.de and I want every visitor always to be redirected to www.example.com Also, all urls must be translated to the corresponding www.example.com URL. Some subfolders are password protected. On top of that I use an SSL certificate for example.com
So in a few lines I want Apache to as follows:
Visitor types this URL -> Apache redirects to (301)
http://example.de -> https://www.example.com
http://www.example.de -> https://www.example.com
http://example.com -> https://www.example.com
http://example.de/path/to/some/file.php -> https://www.example.com/path/to/some/file.php
http://example.de/stats (Login required) -> https://www.example.com/stats (Login required)
I experimented with several .htaccess configurations. My best result manages to redirect the first four cases:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]`
However, I cannot access the password protected folder through a redirection. My browser shows a 401 error message (since the authentication module is executed before the rewrite module). Does anyone have an idea?
Edit: This seems to be the solution. I'm still testing, but it looks ok.
/.htaccess
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
RewriteRule ^(.*)$ - [E=REWRITTEN:1]
/stats/.htaccess
AuthType Basic
AuthName "Members Only"
AuthUserFile /home/.htpasswd
Order Deny,Allow
Satisfy any
Deny from all
Require valid-user
Allow from env=!REWRITTEN