如何将安全和非安全根重定向到登录页面

How to redirect both secure and non-secure root to a login page

我的目标:如果用户导航到根 url (http://localhost), or a secure version of a root url (https://localhost), they will then be redirected to a secure version of the login page (https://localhost/login/index.html).

我的问题:通过导航到描述的url,非安全根的重定向工作正常以上 (http://localhost redirects to https://localhost/login/index.html),但安全版本不起作用,我收到了来自 apache 的 404 错误。

我试图通过在 Apache 的 httpd.conf 文件中使用 Apache RewriteEngine 来完成此操作。我有的是:

#Turn on redirection
RewriteEngine On

# IF someone is trying to access the root directory
RewriteCond %{HTTP_HOST} !^(https://%{HTTP_HOST})?$ [OR]
RewriteCond %{HTTP_HOST} !^(http://%{HTTP_HOST})?$

# Redirect them to the login screen via SSL
RewriteRule ^/$ https://%{HTTP_HOST}/login/index.html [R=301]

以上配置应该与以下逻辑一起工作:

if ( address == SERVER_ROOT ){
    redirectToLoginPageWithSSL();
} else if ( address == HTTPS_SERVER_ROOT ){
    redirectToLoginPageWithSSL();
}

我在 Google/SO 上四处搜索,找到了很多关于如何将根重定向到不同页面的答案,但似乎找不到任何关于如何将安全根重定向到不同的页面。

谢谢, 麦克

如果您的规则在 httpd.conf 文件中,请确保规则是 SSL vhost 非 SSL vhost 的一部分。它们将有所不同,并具有不同的配置容器。您无法匹配非 S​​SL 配置块中的 SSL 请求。此外,%{HTTP_HOST} 变量 只有 主机,没有 "http://".

所以您唯一需要的规则是:

#Turn on redirection
RewriteEngine On

# Redirect them to the login screen via SSL
RewriteRule ^/$ https://%{HTTP_HOST}/login/index.html [R=301]

在 SSL 和非 SSL configuration/vhost 容器中。它看起来像:

<VirtualHost (something)>


</VirtualHost>

另一种方法是在 htaccess 文件中。假设您的 SSL 和非 SSL 站点都指向 相同的文档根目录 文件夹,您可以使用一个 htaccess 文件来影响两者。您只需要:

RewriteEngine On
RewriteRule ^$ https://%{HTTP_HOST}/login/index.html [L,R=301]

请注意,htaccess 文件中的规则正则表达式中没有前导 /