1

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
blubb
  • 55
  • 1
  • 1
  • 10

1 Answers1

0

Try:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^example\.(com|de)$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • @Jon only way around that is to do this: http://stackoverflow.com/questions/7334307/htaccess-basic-auth-by-virtual-host – Jon Lin Dec 20 '13 at 17:04
  • Thanks, your four lines seem to do exactly what the five lines from my question do, too. So, the login problem still occurs. I will read the other thread. – blubb Dec 20 '13 at 18:38
  • The other thread does not help unfortunately. I think the problem is that the .htaccess file in the web root directory (where the RewriteRules are) has priority over the /stats/.htaccess and this messes up the authentication procedure. – blubb Dec 20 '13 at 19:35
  • @user3123203 You need to exclude AUTH (like in the answer) for hosts that are *not* www.example.com, that way, there will be no auth until after the redirect. – Jon Lin Dec 20 '13 at 19:39
  • Thanks. I did not think of that because I did not want to mess around with the password protection. ;) – blubb Dec 20 '13 at 20:12