【问题标题】:Apache: Redirect a folder with basic auth to secure serverApache:将具有基本身份验证的文件夹重定向到安全服务器
【发布时间】:2013-11-15 18:09:48
【问题描述】:
过去,用户使用基本 HTTP 身份验证登录到私人文件夹。我们通过添加 SSL 证书升级了网站,因此现在鼓励这些用户使用 SSL 来保护他们的密码。
为了尝试从 http://example.com/private/ 重定向到 https://example.com/private/,我尝试了这个 .htaccess 文件:
RewriteCond %{HTTPS} =off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
AuthUserFile /usr/home/example/passwd
AuthName "Private Page"
AuthType Basic
问题在于,当用户导航到非 SSL 页面时,它会先要求他们进行身份验证,然后再进行重定向。这违背了整个目的。
【问题讨论】:
标签:
apache
mod-rewrite
https
basic-authentication
【解决方案1】:
您可以尝试拆分重写规则和 mod_auth 指令:
在您放置的虚拟主机中,这将在 perdir .htaccess 之前完成:
RewriteCond %{HTTPS} =off
RewriteRule ^/?private https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
在 /private/.htaccess 中,您只有 mod-auth 指令:
AuthUserFile /usr/home/example/passwd
AuthName "Private Page"
AuthType Basic
【解决方案2】:
如果您使用的是 Apache 2.4,则可以使用 configuration sections 避免双重身份验证。
# Redirect to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
# Authenticate users only when using HTTPS
<If "%{HTTPS} == 'on'">
AuthType Basic
AuthName "Special things"
AuthUserFile /etc/blah.htpasswd
Require valid-user
</If>